Description:
Keyboard Navigator is a suite of React components and hooks for selecting sibling components through the keyboard.
How to use it:
1. Install and import the React Keyboard Navigator.
# Yarn $ yarn add react-keyboard-navigator # NPM $ npm i react-keyboard-navigator
import {
KeyboardNavigatorBoard,
KeyboardNavigatorElement,
useKeyboardNavigator
} from 'react-keyboard-navigator'2. Example app.
const Demo = ({ blocks }: Props) => {
const { markRef } = useKeyboardNavigator({
// prevent the default page scrolling behavior when we are using the keyboard to switch the active state between components
eventCallback: evt => evt.preventDefault()
})
const [highlightBlockIndex, setHighlightBockIndex] = useState(0)
const [boardActive, setBoardActive] = useState(true)
return (
<div>
<div onClick={() => setBoardActive(!boardActive)} style={{ cursor: 'pointer' }}>Active controlled: {boardActive ? '✅' : '❌'}</div>
<hr />
<KeyboardNavigatorBoard
as="main"
markRef={markRef} active={boardActive}
>
{blocks.map((word, index) => (
<KeyboardNavigatorElement
key={word.key}
as="span"
className="block" style={{ top: word.y, left: word.x, borderColor: index === highlightBlockIndex ? 'orange' : 'lightblue' }} onClick={() => setHighlightBockIndex(index)}
markRef={markRef} active={index === highlightBlockIndex} onActiveChange={() => setHighlightBockIndex(index)}
>
{word.text}{' '}
</KeyboardNavigatorElement>
))}
</KeyboardNavigatorBoard>
</div>
)
}





