Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 542
Emisael Carrera Avatar asked Nov 16 '17 15:11

Emisael Carrera


1 Answers

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();
}
like image 144
Vishal Jadav Avatar answered Sep 18 '22 02:09

Vishal Jadav