react2angular
react2angular copied to clipboard
How to share React Context with Angular
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?
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:
- You bootstrap React alongside AngularJS as you normally would, say in a div#react-app by using ReactDOM.render
- The bootstrapped react app offers a way to set its state from the exterior
- 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.
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.
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.