#React question - I have an app that can be rendered multiple times at different roots since it's triggered by #WordPress shortcodes. Whether or not this is a good practice, can I share a component and/or its state between the different roots?
asked on Reddit - https://www.reddit.com/r/webdev/comments/165m6fn/share_component_andor_state_between_multiple/
Thanks!
@bsik Yes, this is possible! You have couple of options:
`createPortal` allows you to render child components into a different DOM element: https://react.dev/reference/react-dom/createPortal. You'd need to pick one of your shortcodes to be the 'main' instance that gets rendered into, and have that also render the others into portals.
Alternatively, you could manage any shared state using an some state management library (Redux, Jotai, etc) and pass the same store into each shortcode's root component.
@jackah thanks for the reply! createPortal is totally new to me, so I'll check that out. I've been reluctant to add a state management library, just because I haven't needed it... yet.
Wondering if you have any thoughts on this - so I simply assigned window.myComponentStateUpdate = myComponentStateUpdate and fired it from the console, and it works... I'm sure this isn't the best way to accomplish it, but it's working. And I'm only trying to 'flip a switch', let something know to update.
@jackah actually don't even bother responding to that, createPortal is *exactly* what I needed. Let's me get rid of the multiple React roots but still render in different areas of the DOM. Damn, thank you! Saved a ton of headache.