Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda