skip to Main Content

I’m trying to execute a function if the user presses the key presented in the component props

const triggerFunc = (e) => {
    if(e.key == props.key) {
      clickFunc()
    }
  }
  React.useEffect(() => {
    document.addEventListener('keydown', triggerFunc)
    return () => {
      document.removeEventListener('keydown', triggerFunc)
    }
  }, [])

I expected this to work but when I press the key set in it nothing happens although it works fine if I set it to the key literally like this if(e.key == 'q')

2

Answers


  1. Chosen as BEST ANSWER

    I have found a simple solution and it was by changing props.key to props.numKey or something


  2. key is one of the internal attributes/props for react components, You need to change the property name from key to something else and it will work fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search