Skip to content

Instantly share code, notes, and snippets.

@asgvard
Created March 17, 2022 13:55
Show Gist options
  • Save asgvard/a2e09723e3353c78c21667f836bac0df to your computer and use it in GitHub Desktop.
Save asgvard/a2e09723e3353c78c21667f836bac0df to your computer and use it in GitHub Desktop.
function GalleryRow({items, focused}) {
const [focusedItemIndex, setFocusedItemIndex] = useState(0);
const onKeyPress = useCallback(({keyCode}) => {
if (!focused) {
return;
}
let newIndex;
if (keyCode === KEY_RIGHT) {
newIndex = focusedItemIndex + 1;
} else if (keyCode === KEY_LEFT) {
newIndex = focusedItemIndex - 1;
}
setFocusedItemIndex(Math.clamp(newIndex, 0, items.length - 1));
}, [focused]);
useEffect(() => {
window.addEventListener('keydown', onKeyPress);
return () => {
window.removeEventListener('keydown', onKeyPress);
};
}, [onKeyPress]);
return (<div>
{items.map((item, index)) => <GalleryItem
key={item.id}
focused={index === focusedItemIndex}
{...item}
/>}
</div>);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment