React, Rails with react-rails and browserify-rails: How to setup and install for Rails 5 project

React, Rails with react-rails and browserify-rails: How to setup and install for Rails 5 project

This article assumes you have already setup a Rails 5 project and you have installed npm locally.

Add these to your Gemfile

gem "browserify-rails"
gem "react-rails"

Run bundle install

bundle install

Add this to your .gitignore

node_modules

Add this to your config/application.rb.

    config.browserify_rails.source_map_environments << "development"
    config.browserify_rails.commandline_options =
       "-t [ babelify --presets [ es2015 react ] ]"
    config.browserify_rails.evaluate_node_modules = true
    unless Rails.env.production?
      # Work around sprockets+teaspoon mismatch:
      Rails.application.config.assets.precompile += ["spec_helper.js"]

      # Make sure Browserify is triggered when
      # asked to serve javascript spec files
      config.browserify_rails.paths << lambda do |p|
        p.start_with?(Rails.root.join("spec/javascripts").to_s)
      end
    end

From the command line, do:

npm install browserify browserify-incremental babelify \
  babel-preset-es2015  react react-dom babel-preset-react --save

Now, let’s create a simpel Hello component similar to that in the React Getting Started tutorial.

We’ll create 2 files:

app/assets/javascripts/components/hello.js

app/assets/javascripts/components.js

// app/assets/javascripts/components/hello.js

import React from 'react'
import ReactDOM from 'react-dom'

class Hello extends React.Component {
  render() {
    return <div> Hello {this.props.name} </div>;
  }
}

export default Hello;
// app/assets/javascripts/components.js

require('babel-polyfill');
window.HelloComponent = global.HelloComponent =
  require("./components/hello").default

All your components will go in this components.js file. Now import the components into the app/assets/javascripts/application.js

//... all your other require statements...
//= require react_ujs
var React = window.React = global.React = require('react');
var ReactDOM = window.ReactDOM = global.ReactDOM = require('react-dom');

require('./components');

Finally, you should be able to use some react_component goodness, so add this to one your views to test it out:

<%= react_component('HelloComponent', name: 'John') %>

That’s all!

Note: If you are getting:

ParseError: 'import' and 'export' may appear only with 'sourceType: module'

You probably have one of two problems:

  1. you have not included react in the config.browserify_rails.commandline_options
  2. You are importing a module that does not exist in your source tree. Make sure to use relative paths.