Middle+
Tell more about the keyboard navigation you implemented.
sobes.tech AI
Answer from AI
Keyboard navigation is the ability to control the application's interface using the keyboard, which is important for accessibility and user convenience.
In one project, I implemented navigation through a list of items using the up/down arrows, as well as support for Enter and Escape keys for selecting and canceling actions. I used keydown event handlers on the list container, tracked the current focus, and programmatically changed it.
Here's an example of implementing list item navigation in React:
const List = ({ items }) => {
const [focusedIndex, setFocusedIndex] = React.useState(0);
const listRef = React.useRef(null);
React.useEffect(() => {
const handleKeyDown = (e) => {
if (e.key === 'ArrowDown') {
setFocusedIndex((prev) => Math.min(prev + 1, items.length - 1));
} else if (e.key === 'ArrowUp') {
setFocusedIndex((prev) => Math.max(prev - 1, 0));
} else if (e.key === 'Enter') {
alert(`Selected item: ${items[focusedIndex]}`);
}
};
const currentList = listRef.current;
currentList.addEventListener('keydown', handleKeyDown);
return () => currentList.removeEventListener('keydown', handleKeyDown);
}, [items, focusedIndex]);
return (
<ul tabIndex={0} ref={listRef} style={{ outline: 'none' }}>
{items.map((item, index) => (
<li
key={item}
style={{ background: index === focusedIndex ? '#bde4ff' : 'transparent' }}
>
{item}
</li>
))}
</ul>
);
};
This approach improves UX and makes the application more accessible for users with disabilities.