react_on_rails icon indicating copy to clipboard operation
react_on_rails copied to clipboard

React On Rails w/Hotwire and Turbo Streams

Open braindeaf opened this issue 2 years ago • 6 comments

Is there any information how to get React components to render after Turbo Stream updates? I'm got a few components which don't render when our modals update and since turbo don't have a 'after-stream-render' Event. When the modal opens I trigger ReactOnRails.reactOnRailsPageLoaded(); so that's fine but I can't work out how I can trigger this on Turbo Streams.

We are still on 11.3.0 if that makes a difference.

Many thanks :)

braindeaf avatar Nov 14 '22 23:11 braindeaf

Here is where the event listeners get installed.

https://github.com/shakacode/react_on_rails/blob/master/node_package/src/clientStartup.ts#L247-L278

I'm open to a PR.

Thanks,

Justin

justin808 avatar Nov 26 '22 04:11 justin808

I will take a look, thank you :)

braindeaf avatar Nov 26 '22 09:11 braindeaf

Workaround I found (from https://github.com/shakacode/react_on_rails/issues/1508)

const debouncedHandlerForNodes = debounce(() => {
  const nodes = document.querySelectorAll("[data-signal-react-rerender]");
  if (nodes.length) {
    ReactOnRails.reactOnRailsPageLoaded();

    nodes.forEach((each) => each.remove());
  }
}, 100);

document.addEventListener("turbo:before-stream-render", function () {
  debouncedHandlerForNodes();
});

where debounce function is

function debounce(func: Function, wait: number, immediate: boolean = false) {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      timeout = null;
      if (!immediate) func.apply(context, args);
    }, wait);
    if (immediate && !timeout) func.apply(context, args);
  };
}

You must render some div or span being hidden with data-signal-react-rerender. Render this element as children of node you're replacing from turbo stream.

You could do this without searching for the node but you will probably get warnings. Also you need this debounce as this event gets fired twice I think. Without delay this won't work, rerender would not happen.

uvera avatar Jan 20 '23 12:01 uvera

@Judahmeek @ahangarha @uvera can the workaround go into a PR, being sure not to break existing functionality?

justin808 avatar Jul 25 '23 23:07 justin808

Hi, I came across this awesome repository and have a few questions.

  • Can I use the turbo streams with react?
  • Which hotwire turbo and stimulus version of used in the react_on_rails? What is different?
  • Can I upgrade to the latest hotwire turbo and stimulus library version easily?

burakakca avatar Aug 01 '24 21:08 burakakca

@burakakca #1620 may answer some of your questions.

Judahmeek avatar Aug 17 '24 19:08 Judahmeek