Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to share React Context with Angular #113

Open
raubel opened this issue Oct 8, 2019 · 3 comments
Open

How to share React Context with Angular #113

raubel opened this issue Oct 8, 2019 · 3 comments

Comments

@raubel
Copy link

raubel commented Oct 8, 2019

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?

@cozmy
Copy link

cozmy commented Mar 10, 2020

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.

@seahorsepip
Copy link

seahorsepip commented Apr 20, 2020

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.

@raubel
Copy link
Author

raubel commented Mar 11, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants