I have a project on Rails 6.
Started migrating it to React by using react-rails
. However, there are still some components which I cannot migrate to React ATM due to time limitations.
I want to be able to use the old component (partial
) in my React component.
e.g let's say I have a React component:
Component.tsx
export const Component = ({post}) => {
return <div>
<ShareButton post={post}/>
</div>
}
and somehow the ShareButton should contain this:
<%= render partial: 'posts/shared/share_post_btn', locals: {event: false, post: post} %>
I read that it may be possible by using .jsx.erb
but I couldn't figure out how.
Would love to get some insights! Thank you.
CodePudding user response:
I'm afraid you'll be mixing build pipelines here. The .erb is parsed by the asset pipeline, which was the default for Rails <6 and still for CSS, but this doesn't work no longer by default for yarn/webpacker-based builds that Rails 6 favoured for JS output (Rails 7 choose a new path again, I'm sorry).
Also, as components typically have actions attached, I don't really see how a mixed Rails (static HTML) based approach could work.
A few ideas:
- In the end, both Rails/ERB and React create HTML. Perhaps you can simply create the same HTML that your ShareButton creates with Rails as a temporary workaround? You'd share the CSS from the new front-end project, and you can slowly migrate rebuilding components in React (when you're thinking of building component library, make sure it works with stand alone HTML/CSS).
- You can load static HTML in React using dangerouslysetinnerhtml; that might be a solution if you have complex prerendered text you want to load within a React component.
- Load React client side (relatively slow); wouldn't really do this for production: How to perform import/export in client-side React JSX using Babel-Standalone
- Do some parsing of the HTML received in React; and render components conditionally (this approach is a bit how Rails Turbo works; a more Rails-native answer to React, Vue and the like)
- Push through: none of the 'solutions' above are really satisfying if you want to end up with a clean React version.
- Roll back: why use react in the first place. React is just another fancy way of rendering HTML.