What is the preferred way to pass data from a Rails view to a react component in Rails 6?

Viewed 709

I know that the react_on_rails and the react-rails gems have ways of passing data to react components. For example, you can do things like this: <%= react_component("HelloWorld", props: @some_props) %>.

Now that we can do rails new myapp --webpack=react and have javascript packs, how can I pass data, or props, from my rails views to my react components? Can I do something like: <%= javascript_pack tag 'hello_react', data: @users %>?

I don't want to have to build out an api, and it seems there isn't a preferred way to accomplish what I want. The only feasible method I have seen so far was in this article.

1 Answers

I think the most elegant way is by using react_rails

in rails 6 the steps is first you need to add react rails

Gemfile

gem 'react-rails'

then run the generator rails generate react:install

if you not yet install webpacker/rails you need to do that first

rails webpacker:install
rails webpacker:install:react
rails generate react:install

then generate your first react component with the generator

rails g react:component HelloWorld greeting:string

next render it in your html.erb with the view_helper from the gem

<%= react_component("HelloWorld", { greeting: "Hello from react-rails." }) %>

first parameter is the react files name and the second is the props

Related