Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass an event parameter to an event listener declared in a useEffect in React?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading