Simple and straightforward solution to get the next logical record.
Live Demo
https://serhat-m.github.io/moveNext
Install
npm i movenext
Usage
Function moveNext(opts)
import moveNext from "movenext"
opts
Object
data
{ [key: string]: any }[]
array of recordsdirection
'prev' | 'next'
determines the directionendBehaviour
'default' | 'jump'
behaviour after the last logical entryselector(entry) => any
callback for selecting the id reference
entry
{ [key: string]: any }
entry of data
selectedId
undefined | ...
current selected id
@returns
new selected id
Example
This example navigates through the data
Array, if the keyboard keys ArrowDown
or ArrowUp
are pressed. The selectedId
variable saves the current state.
import moveNext from "movenext"
const data = [
{ id: 1, title: "Dataset 1" },
{ id: 2, title: "Dataset 2" },
{ id: 3, title: "Dataset 3" },
]
let selectedId = undefined
document.addEventListener("keydown", (event) => {
const direction = event.key === "ArrowDown" ? "next" : event.key === "ArrowUp" ? "prev" : false
if (direction) {
selectedId = moveNext({
data,
direction,
endBehaviour: "default",
selector: (entry) => entry.id,
selectedId,
})
}
})
Example React
import moveNext from "movenext"
const [data, setData] = useState([
{ id: 1, title: "Dataset 1" },
{ id: 2, title: "Dataset 2" },
{ id: 3, title: "Dataset 3" },
])
const [selectedId, setSelectedId] = useState(undefined)
const keyDownHandler = useCallback(
(event) => {
const direction = event.key === "ArrowDown" ? "next" : event.key === "ArrowUp" ? "prev" : false
if (direction) {
setSelectedId((prevSelectedId) => {
return moveNext({
data,
direction,
endBehaviour: "default",
selector: (entry) => entry.id,
selectedId: prevSelectedId,
})
})
}
},
[data],
)
useEffect(() => {
document.addEventListener("keydown", keyDownHandler)
return () => {
document.removeEventListener("keydown", keyDownHandler)
}
}, [keyDownHandler])
TypeScript
The following types are available and can be used to define e. g. typed helper functions:
Direction = "prev" | "next"
EndBehaviour = "default" | "jump”
import type { Direction, EndBehaviour } from "movenext"
function updateData(direction: Direction, behaviour: EndBehaviour) {
...
}
const direction: Direction | false = event.key === "ArrowDown" ? "next" : event.key === "ArrowUp" ? "prev" : false