2

I am new to reactjs. I want communication to happen between two independent components.

These components are not having any parent child relationship.

I found this piece of code.

I dont know how to use it https://medium.com/react-zine/how-to-communicate-between-components-in-react-cc1ee986523a

Priya
  • 1,453
  • 4
  • 29
  • 55
  • 1
    possible duplicate of [ReactJS Two components communicating](http://stackoverflow.com/questions/21285923/reactjs-two-components-communicating) – Pete TNT Aug 12 '15 at 07:55

1 Answers1

13

From the docs:

For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. Flux pattern is one of the possible ways to arrange this.

We use the PubSub pattern to attach global events, but as the docs say you can use many different arrangements.

Example using PubSub

Receiver component:

componentDidMount: function() {
    this.token = PubSub.subscribe('MY TOPIC', this.subscriber)
},
componentWillUnmount: function() {
    PubSub.unsubscribe(this.token)
},
subscriber: function(msg, data) {
    console.log(msg, data)
    // set state etc...
})

Emitter:

PubSub.publish('MY TOPIC', 'hello world!')
knowbody
  • 8,106
  • 6
  • 45
  • 70
David Hellsing
  • 106,495
  • 44
  • 176
  • 212