mstdn.social is one of the many independent Mastodon servers you can use to participate in the fediverse.
A general-purpose Mastodon server with a 500 character limit. All languages are welcome.

Administered by:

Server stats:

12K
active users

bsik

question - I have an app that can be rendered multiple times at different roots since it's triggered by 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 - reddit.com/r/webdev/comments/1

Thanks!

redditShare component and/or state between multiple React rootsSo, this is probably not a great way to structure this, but I have a React app that is triggered by a shortcode in Wordpress. If there are...

@bsik Yes, this is possible! You have couple of options:

`createPortal` allows you to render child components into a different DOM element: react.dev/reference/react-dom/. 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.

react.devcreatePortal – ReactThe library for web and native user interfaces

@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.