3

I'm new at react & coding. I want to run a function if space & up arrow pressed. i want to run my jump() function

const jump = () => {
    if (onJump == false){
        $("#dino").animate({top:'-=60%'}, 300);
        $("#dino").animate({top:'+=60%'}, 300);
        onJump=true;
        setTimeout(function() {
          onJump=false;
        },600)
    }
}

i already try several codes but none of them are working.

2 Answers 2

5
useEffect(() => {
 window.addEventListener('keydown', e => {
  if(e.key === 'Enter'){ // See key codes https://keycode.info
   console.log('You pressed Enter')
  }
 })
},[])

EDIT

the best practice for performance is to remove the event listener on un-mount:

useEffect(() => {
 const onKeyDown = (e) => {
  if(e.key === 'Enter'){
   console.log('You pressed Enter')
  }
 }

 window.addEventListener('keydown', onKeyDown)
 return () => window.removeEventListener('keydown', onKeyDown)
},[])
Sign up to request clarification or add additional context in comments.

4 Comments

why when i press the key, the function will run twice?
@Green_Sand did you wrap the code inside the useEffect()? useEffect(() => { window.addEventListener(...) }, [])
@Green_Sand Take a look, i edited my answer
thank you bro, i didn't use useEffect before
1

If you don't need to focus on any element and want to listen to keyboard events, you need to add listener to the window object. Here is the solution for spacebar key be pressed down and key up event of up key

import React, { useRef } from 'react';

function KeyUpHandler() {

    const keysPressedDown = useRef({});

    useEffect(() => {
        window.addEventListener("keydown",
            (event) => {
                // space
                if (event.keyCode == 32) {
                    keysPressedDown.current[event.keyCode] = true;
                }
                // up
                if (event.keyCode == 38) {
                    keysPressedDown.current[event.keyCode] = true;
                }
            }, false);
        window.addEventListener("keyup",
            event => {
                // space
                if (event.keyCode == 32) {
                    keysPressedDown.current[event.keyCode] = false;
                }
                if (keysPressedDown.current[32] && event.keyCode == 38 &&
                    keysPressedDown.current[38]) {
                    // call your function here 
                    console.log(' space and up ');
                }
                // up
                if (event.keyCode == 38) {
                    keysPressedDown.current[event.keyCode] = false;
                }
            }, false);
    }, []);

    return <></>

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.