react2angular icon indicating copy to clipboard operation
react2angular copied to clipboard

How to share React Context with Angular

Open raubel opened this issue 5 years ago • 3 comments

My React component relies on a React Context, using a Context Consumer. Since my Angular app does not bootstrap any React component hierarchy, my Context Provider is not initialized. Do you have any advice to have an initialized Context when my React component is rendered?

raubel avatar Oct 08 '19 10:10 raubel

Hey @raubel , this is possible but it requires a fork of react2angular. At my company, we already implemented this and it works fine.

Here's the gist of it:

  1. You bootstrap React alongside AngularJS as you normally would, say in a div#react-app by using ReactDOM.render
  2. The bootstrapped react app offers a way to set its state from the exterior
  3. react2angular doesn't do a ReactDOM.render anymore but instead it sets the state of the bootstrapped react app with a ReactDOM.createPortal which will be put in the this.$element[0]

In the end, the bootstrapped react app will hold on its state all the render functions which setPortals on AngularJS Elements. It works fine and they all share the same context. Hope this helps.

cozmy avatar Mar 10 '20 08:03 cozmy

I've created a library to resolve this: react2angular-shared-context

It uses portals as suggested above but is not dependant on how react2angular works. It also handles props changes from angular and the component life cycle e.g. unmount.

seahorsepip avatar Apr 20 '20 10:04 seahorsepip

More than three years after, I have the opportunity to come back to my problem and apply your solution. And it works like a charm! Thank you both of you, @cozmy and @seahorsepip.

raubel avatar Mar 11 '23 04:03 raubel