Reputation: 65
I have the following scenario:
1) Left and right directional keys and enter key can be pressed
2) I can use useState
to store which key was pressed (whether it was the left or right key)
3) After that, when pressing the enter key, I need to know which was the last key pressed: left or right
I can't do item 3.
Upvotes: 2
Views: 587
Reputation: 65
resolution as follows:
const [active, setActive] = useState(1);
const onKeyDownEnter = (): void => {
switch (active) {
case 1:
console.log('left pressed');
break;
case 2:
console.log('right pressed');
break;
default:
break;
}
const onKeyDown = useCallback((event: KeyboardEvent) => {
const key = mapKeyEvent(event);
switch (key) {
case KEYS.NAV_LEFT:
setActive(1);
break;
case KEYS.NAV_RIGHT:
setActive(2);
break;
case KEYS.NAV_ENTER:
onKeyDownEnter();
break;
default:
break;
}
}, [activeElement]);
useEffect(() => {
document.addEventListener('keydown', onKeyDown);
return (): void => {
document.removeEventListener('keydown', onKeyDown);
};
}, [onKeyDown]);
Upvotes: 1
Reputation: 491
You can use useRef() for this.
const prevKeyPressRef = useRef();
useEffect(() => {
prevKeyPressRef.current = currentKeyPress;
});
const prevKeyPress = prevKeyPressRef.current;
Upvotes: 1
Reputation: 897
If you got (2), then you have "left" or "right" stored as state. Just attach another listener that would listen to Enter keypress (code === 13) with a callback to display that state (from 2).
Upvotes: 0