Skip to content Skip to sidebar Skip to footer

How To Communicate Reactdom.render With Other Reactdom.render

I have a project that includes React applications and other HTML elements. It means: ReactDOM.render(, document.getElementById('element1')

Solution 1:

In order for two React components to efficiently communicate by means of React alone, they should communicate through common parent.

In case of two unrelated widgets, they can be rendered as portals with a common parent, as suggested in this answer:

<divid="App"></div><h2>Foo widget</h2><divid="FooWidget"></div><h2>Bar widget</h2><divid="BarWidget"></div>

classAppextendsComponent {
  render() {
    state = {
      foo: 'foo',
      setFoo(foo) {
        this.setState(state => ({...state, foo}));
      }
    };

    return<FoobarContext.Providervalue={this.state}>    
      {ReactDOM.createPortal(<FooWidget />, document.getElementById('FooWidget'))} 
      {ReactDOM.createPortal(<BarWidget />, document.getElementById('BarWidget'))} 
    </FoobarContext.Provider>;
  }
}

constFooWidget = props => <FoobarContext.Consumer>
  {({ foo }) => foo}
</FoobarContext.Consumer>;

...

ReactDOM.render(<App />, document.getElementById('App'));

Components can communicate through foo context property by using setFoo setter.

An alternative that can make use of ReactDOM.render is to use Redux and connect two unrelated components to same store. They can communicate through common store.

Solution 2:

You would have various option like subscribing to events between the app:

// App #1const event = newEvent('start');
// Dispatch the event.
elem.dispatchEvent(event);


// App #2 Listen for the event.componentDidMount() {
  elem.addEventListener('start', this.start }, false);
}

start = (e) => {
  // ....
}

componentWillUnmount() {
  elem.removeEventListener('start');
}

The point anyway is you should use a global store like Redux picking component you need from both apps as this kind of solution are very diffucult to maintain.

Post a Comment for "How To Communicate Reactdom.render With Other Reactdom.render"