Search code examples
reactjskeyboard-eventsonkeypress

React onkeypress event to run a function


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.


Solution

  • 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)
    },[])