Home > Software engineering >  How can I pass an event parameter to an event listener declared in a useEffect in React?
How can I pass an event parameter to an event listener declared in a useEffect in React?

Time:02-26

I've found a handful of questions that ask of similar things, but none that satisfy all the criteria that I have to meet. I am trying to attach an event listener to the document within useEffect, then remove it with the useEffect return callback function. The problem lies in the fact that my listener function requires an event parameter to check which key was pressed.

import { useEffect } from 'react';

function Board() {
    useEffect(() => {
        document.addEventListener('keyup', commit);

        return () => {
            document.removeEventListener('keyup', commit);
        }
    }

    const commit = (event) => {
        if(event.target.keyCode === '13') {
            console.log('Enter key pressed');
        }
    }

    return (
        <div className="Board">
            This is my component
        </div>
    )
}

This will never console.log anything because there is no event variable being passed to the listener.

CodePudding user response:

You can access directly key from event object in eventHandler( commit fn) and pass a empty dependency array to useEffect

import { useEffect } from 'react';

function Board() {
    useEffect(() => {
        document.addEventListener('keyup', commit);

        return () => {
            document.removeEventListener('keyup', commit);
        }
    },[])

    const commit = (event) => {
        if(event.key === 'a') {
            console.log('Enter key pressed',event.key);
        }
    }

    return (
        <div className="Board">
            This is my component
        </div>
    )
}
  • Related