I have a child component that need to listen to one of it's parent event
. More precisely, I have a function in the child component that takes as parameter an event
from the parent. I would like to call this function everytime the event
occurs.
As an example, here is a code snippet:
class Parent extends React.Component {
handleKeyDown = (event) => {
// Call the child function doSomething()
}
render() {
return (
<input
type="text"
onKeyDown={this.handleKeyDown}
>
<Child />
)
}
}
class Child extends React.Component {
doSomething = (event) => {
// Get the event from parent
}
render() {
return (
...
)
}
}
I have considered two ways to do it:
- Using
ref
to call the child function from the parentonKeyDown
(supposing that I can access it) - Using a
state
to store the event and pass it as aprops
to the child, then listen toprops
changes withgetDerivedStateFromProps
.
However, none of these solutions seems very appealing. I have also thought about using a redux function but I need data from the child component as well as the event
from the parent component... I was wondering if there is a clean way do to that?