Open multiplegeorges opened 3 years ago
Thanks very much!
is this a solution when the react component not attached/loaded in the page that reloaded using turbo?
@buncis Yes, this code should help when you need to initialize a React component that is lazy loaded in a Turbo Frame after the initial page load.
Hey all,
Like many others, I've been experimenting with Turbo and Turbo Frames. We have a large set of one-off React components we like to sprinkle into our templates using react-rails and that pattern works great for enhancing interactivity.
But, like many others, we quickly realized that Turbo doesn't emit any events when a frame loads. This is by design and their logic makes sense.
To fix this we've put together a quick proof of concept MutationObserver that watches the document tree for changes. These changes could come from any source, but in our case it's always a Turbo Frame load. I don't think there any need to differentiate based on the source of the change.
We've simply added this to our application.js pack file and we've found that this works quite well.
Hopefully this helps someone else out and/or starts a discussion about moving react-rails to this model for mounting/unmounting components. It's a lot more robust than watching for Turbo events, I think, but I'm sure there's a ton of edge cases covered by the existing code.
Cheers!