I have React on Rails set up for my project. I have a haml template that renders a React component:
-# my_template.haml
%div
= react_component('MyComponent')
Now, if I render this template inside of another template, it works as expected, and I see the rendered React component.
-# my_other_template.haml
%div
= render 'my_template'
However, if I reference the component or the template that renders the component inside of a capture_haml block, it does not render:
-# my_other_template.haml
- captured = capture_haml do
-# This does not work
= react_component('EliteSellerBadge')
-# This does not work
= render 'my_template'
%div
-# This works
= react_component('EliteSellerBadge')
-# This works
= render 'my_template'
-# This does not work
= captured
In the cases that work, the react component will render inside of a div with a unique id like MyComponent-react-component-0b88d3fe-e457-4bec-b2a1-119097662161, and will have a script tag next to it with the id js-react-on-rails-context. In the cases that do not work (inside the capture_haml blocks), the div with the unique id is rendered, but it is empty, and no js-react-on-rails-context script tag appears in the DOM.
Is it not possible to use a React on Rails component inside of a capture_haml block like this, or am I just doing something wrong?
I know this has been a while but I also had an issue where the contents are on the DOM as described in the question but the react component didn't render on the browser. I think in a situation like this, you'd need to prerender the react component by doing;
In my case, the view that had the component I needed to render was added with an xhr request and jquery
replaceWithmethod.Hope this does help somebody.
PS: You might run into issues with prerender if you are referencing global objects like
windowanddocumentin your react components.