React on Rails: react-rails gem
Part one in a short series on using React with Rails.
The react-rails gem is a like shiny, red, ‘Easy’ button for getting React.js working on Rails. This is how to get started.
The setup
1. Add this to your Gemfile:
gem 'react-rails', github: 'reactjs/react-rails'
This looks a little funky because you’re bundling in the github version directly. Life on the bleeding edge, and all. Once 1.0 gets released you’ll be able to drop the suffix.
Run `bundle` in the root of your application.
2. Run the install script:
rails g react:install
This does a few nifty things:
- Creates a /components directory for components
- Creates a components.js manifest, requiring the /components directory
- Adds react.js, react-ujs.js, and components.js to your application.js manifest
Writing a component
Now you’re geared up to write a component. Let’s create it in our freshly minted /components directory.
// app/assets/javascripts/components/greeting.js.jsxvar Greeting = React.createClass({
render: function () {
return <h1>Hi {this.props.name}!</h1>;
}
});
The .js.jsx suffix tells Rails “Here be JSX. Sort that out before you do the JavaScript thing.”
Save that puppy and you’re ready to go.
Adding components to a views
react-rails comes with a handy little helper for adding components to rails views. It’s called react_component. It’s takes two arguments*:
- a component name
- a props hash
<%= react_component('HelloMessage', { name: 'Bob' }) %>
This helper takes advantage of react-ujs to appropriately mount and unmount components when pages loads.
What about CoffeeScript?
Both ES6 Harmony and CoffeeScript are supported. ES6 Harmony requires additional configuration and CoffeeScript has JSX-concerns that need to be worked around. Be sure to consult the documentation.
Next Steps
Now that you’re setup with react-rails, you might be wondering if there are other react libraries you should be using.
Next up, we’ll take a look rails-assets and how to bundle JavaScript libraries, assets, and components into your Rails apps.
All examples may be found here: https://github.com/learnreact/react-on-rails/tree/react-rails
* There’s an optional third argument that allows you to specify the tag_name used by the helper. `div` is used by default