reactjsruby-on-railsrubyerbreact-rails

How can I use ERB inside a React component? [Rails 6]


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.


Solution

  • 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: