Build a dropdown component with keyboard navigation.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
import React, { useState, useEffect, useRef } from 'react';
function Dropdown({ options }) {
const [isOpen, setIsOpen] = useState(false);
const [focusedIndex, setFocusedIndex] = useState(-1);
const ref = useRef(null);
useEffect(() => {
const handleKeyDown = (e) => {
if (!isOpen) return;
if (e.key === 'ArrowDown') {
setFocusedIndex(i => (i + 1) % options.length);
} else if (e.key === 'ArrowUp') {
setFocusedIndex(i => (i - 1 + options.length) % options.length);
} else if (e.key === 'Enter') {
// select option
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [isOpen, options.length]);
return (
<div ref={ref}>
<button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
{isOpen && (
<ul>
{options.map((option, i) => (
<li key={option} style={{ backgroundColor: i === focusedIndex ? 'lightgray' : 'white' }}>
{option}
</li>
))}
</ul>
)}
</div>
);
}
export default Dropdown;