Hitsugaya
Hitsugaya

Reputation: 65

React functional component listener

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

Answers (3)

Hitsugaya
Hitsugaya

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

Paul Ryan
Paul Ryan

Reputation: 491

You can use useRef() for this.

const prevKeyPressRef = useRef();
useEffect(() => {
  prevKeyPressRef.current = currentKeyPress;
});
const prevKeyPress = prevKeyPressRef.current;

See the docs here

Upvotes: 1

rtviii
rtviii

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

Related Questions