How to Listen for Events in children components in React Native?

Emisael Carrera picture Emisael Carrera · Nov 16, 2017 · Viewed 10.6k times · Source

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?

Answer

Vishal Jadav picture Vishal Jadav · Nov 17, 2017

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();
}