I have a child ponent nested in a parent ponent. I want the parent ponent to get notified whenever an event takes place in a child ponent. In Vue, I could do this:
// inside the child ponent EventButton
// the event 'someEvent' gets emitted whenever the button is clicked
<button @click="$emit('someEvent')">
Emit event
</button>
// inside the parent ponent
<EventButton @someEvent="() => do something" />
How can I achieve the same functionality in React?
Some clarification: I want an event to be emitted to the parent ponent whenever I like e.g., when an item has been added to a list, and not just when a button is clicked.
I have a child ponent nested in a parent ponent. I want the parent ponent to get notified whenever an event takes place in a child ponent. In Vue, I could do this:
// inside the child ponent EventButton
// the event 'someEvent' gets emitted whenever the button is clicked
<button @click="$emit('someEvent')">
Emit event
</button>
// inside the parent ponent
<EventButton @someEvent="() => do something" />
How can I achieve the same functionality in React?
Some clarification: I want an event to be emitted to the parent ponent whenever I like e.g., when an item has been added to a list, and not just when a button is clicked.
Share edited Dec 20, 2022 at 14:02 murkut23 asked Dec 20, 2022 at 13:55 murkut23murkut23 691 silver badge5 bronze badges 1- onClick={() => console.log("clicked")} – terpinmd Commented Dec 20, 2022 at 13:58
1 Answer
Reset to default 7One way you can achieve this is to give to the child ponent as props a function defined in the parent ponent.
In parent:
function notify_me(){
#do what you want to do in the parent ponent using a state for example
}
At the child definition:
<Child notify_parent ={notify_me} />
In Child ponent:
<EventButton @someEvent={() => props.notify_parent()}/>