Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
    )
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda