Home > Software design >  How to pass an onKeyDown event as a prop to parent component?
How to pass an onKeyDown event as a prop to parent component?

Time:08-14

I have an input with an onChange attribute and an onKeyDown attribute. The onChange attribute receives a value of {(e) => props.change(e)} and in the parent component I assign the change prop to a handleChange function. I want to do the same thing with my onKeyDown attribute, however I face two issues:

When I use {(e) => props.key(e)}, Chrome Devtools says that key is not a prop. When I try passing {key} instead of (props) to the child component, Chrome Devtools says that key is not a function.

I'm trying to pass the prop so that I can consume the key code value in the parent component and execute some logic.

I've also tested to make sure the function is working within Home.js. If someone could give a solution and an explanation as to why this happens I would be appreciative.

Here is an example of my code:

/ App.js

export default function App() {
const key = (e) => {
  if (e.keyCode === 8) {
   ...
  }
}

const change = (e) => {
  return ...
}

return
<Home
  key={key}
  change={change}
/>
}

/ Home.js
export default function Home(props) {
return 
<input
  onChange={(e) => props.change(e)}
  onKeyDown={(e) => props.key(e)}
/>
}

CodePudding user response:

key is a special prop in React and gets special treatment:

[…] there are two special props (ref and key) which are used by React, and are thus not forwarded to the component.

So it should work if you change the name of the prop:

App.js

export default function App() {
// …
return
<Home
  myKey={key}
  change={change}
/>
}

Home.js

export default function Home(props) {
return 
<input
  onChange={(e) => props.change(e)}
  onKeyDown={(e) => props.myKey(e)}
/>
}
  • Related