React and Ruby on Rails play very nicely together if you are using the react-rails gem. Using react-rails, you can easily drop in React components throughout your Rails application. In this lesson, we will get react-rails installed and create our first React component.
The first thing we need to do to use react-rails is add it to our Gemfile, so we're going to add react-rails down here at the bottom of our Gemfile. We're going to target version 1.5 of the react-rails gem. Now that we've added that to the Gemfile, we can open up the terminal and type "bundle install," and there we go. We've installed the react-rails gem.
Inside of that folder, you'll see a new file called "components.js." Inside of that, you can see that react-rails has required the full tree of the components folder, which is empty right now, but we'll fill it up with components soon.
Now that we have react-rails configured, I can open the terminal. I can use the supply generator by calling "rails generate react:component."
We're going to name our component "message," and I'm going to give it a property of "text," which is a string. Finally, I'm going to say, "--ES6" to give us an EF6 class in the generated component.
Inside of the components folder, you'll see that we have "message.es6.jsx." The generator has given us a class that extends react.component, as well as given prop types for the text property and a render method that returns a simple div, and it just displays this text property.
To get our component to display in our template, we're going to come down here into "index.html.erb," and what we're going to do is add the react-rails react component helper. Its argument is going to be the name of our component, or in this case "message."
Now we'll refresh the browser and, voila, we have text. The text property isn't displaying any value, so we can help that out here by adding another argument "text: ." We'll just send a simple string in. We'll call it "Hello."
Come over here, and we'll refresh the browser, and there you go. Our property shows up. "Text equals hello."
Now we can make a couple copies of this component, and we can change the text. We'll change this to "Goodbye," and we'll change this one to "It is alive," and we'll refresh the browser. We see that we have three copies of this component with three different values for the text property.