Issue with Rails UJS and Dynamically Loaded ERB Content via React Component

Hello everyone,

I’m currently working on a Rails application that incorporates React for certain parts of the UI. I’ve encountered an issue that I believe is related to Rails UJS and how it interacts with content loaded dynamically into a React component.

The Setup:

  • My application uses Rails 7 views (ERB) for most parts but includes a React component for specific sections of the page.
  • I’m utilizing esbuild along with Stimulus controllers to integrate React components.
  • I have two controllers: api/v1/projects_controller which serves JSON responses for the React component and will be used for smartphone applications, and dashboard/projects_controller which serves HTML responses for the ERB templates.
  • The React component fetches HTML content from the dashboard/projects_controller via Axios and injects it into the component’s DOM using dangerouslySetInnerHTML.

The Issue:

  • The dynamically loaded ERB content contains links and forms that should be handled by Rails UJS (e.g., data-method="delete", data-confirm="Are you sure?", etc.), but these UJS features do not work on the loaded content.
  • It seems that Rails UJS event handlers are not attached to the new content inserted into the DOM by the React component.

Attempts at Resolution:

  • I tried manually re-initializing Rails UJS after the content is loaded, but I couldn’t find a reliable way to reapply the UJS behaviors to the new content.
  • I’ve ensured that Rails UJS is included and started in my JavaScript pack.

Questions:

  1. How can I ensure that Rails UJS correctly attaches its event handlers to HTML content loaded dynamically via a React component?
  2. Is there a recommended approach to integrate Rails UJS with content fetched and injected by React in this manner?

Any insights, suggestions, or guidance on how to resolve this issue would be greatly appreciated. I’m looking to maintain the Rails way of handling forms and links with UJS while leveraging React for a more dynamic user experience.

Thank you in advance for your help!