I want to implement an event listener from parents to children components in my React Native app, I'm using a StackNavigator as a router.
How can I listen for events occurred in the top/parent components?
Simply use React Native's DeviceEventEmitter
.Emit your event from parent component like below:
DeviceEventEmitter.emit('eventKey', {name:'John', age:23});
and listen event in children component
componentDidMount(){
//add listener
this.eventListener = DeviceEventEmitter.addListener('eventKey',this.handleEvent);
}
handleEvent=(event)=>{
//Do something with event object
}
componentWillUnmount(){
//remove listener
this.eventListener.remove();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With