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

209
Visualizações
How to make 2 window event listener in react js

i want to run a function when the arrowdown button is pressed &un a function again if the arrowdown button isn't pressed.

const Gamefile = () => {
useEffect(() => {
    window.addEventListener('keydown', e => {
     if(e.key === 'ArrowDown'){
        duck();
    }
     }
   
     )
    window.addEventListener('keyup'), e => {
        if(e.key === 'ArrowDown'){
            notduck();
        }
    }
    })
}

i tried this code but it's error, "Expected an assignment or function call and instead saw an expression no-unused-expressions"

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

0

Second addEventListener is wrong. You are passing just one argument, the listener function is not passed.

const Gamefile = () => {
        useEffect(() => {
            window.addEventListener('keydown', e => {
                if (e.key === 'ArrowDown') {
                    duck();
                }
            });
            window.addEventListener('keyup', e => {
                if (e.key === 'ArrowDown') {
                    notduck();
                }
            });
        });
    };

Also, I would recommend you add a cleanup function for this hook to remove listeners when they are not necessary.

about 4 years ago · Juan Pablo Isaza Relatório

0

Simple mistake, you accidentally closed your bracket too early, so you weren't passing in the function.

const Gamefile = () => {
    useEffect(() => {
        window.addEventListener('keydown', e => {
            if (e.key === 'ArrowDown') {
                duck();
            }
        })
      
        window.addEventListener('keyup', e => {
            if (e.key === 'ArrowDown') {
                notduck();
            }
        })
    })
}

I would also personally recommend switching the key-tracking over to a hook. I wrote a quick hook that handles this, and cleans up the events as well.

const useButtons = () => {
  const [pushed, setPushed] = useState([]);

  useEffect(() => {
    const handlePress = (event) => {
      setPushed((previous) => {
        return [...new Set([...previous, event.keyCode])];
      });
    };

    const handleUnpress = (event) => {
      setPushed((previous) => {
        return previous.filter((key) => event.keyCode !== key);
      });
    };

    window.addEventListener("keydown", handlePress);
    window.addEventListener("keyup", handleUnpress);

    return () => {
      window.removeEventListener("keydown", handlePress);
      window.removeEventListener("keyup", handleUnpress);
    };
  });

  return { pushed };
};

This really cleans up the usage, which looks as follows.

const App = () => {
  const { pushed } = useButtons();

  return (
    <>
      <h1>Pushed Buttons</h1>
      <code>{pushed.toString()}</code>
    </>
  );
};

ReactDOM.render(<App />, document.getElementById("container"));
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