React on Rails integrates Rails with (server rendering of) Facebook's React front-end framework.

Features and Why React on Rails? Given that rails/webpacker gem already provides basic React integration, why would you use "React on Rails"? Server rendering, often used for SEO and performance, is not offered by rails/webpacker.

* The easy passing of props directly from your Rails view to your React components rather than having your Rails view load and then make a separate 1request to your API. * Redux and React Router integration. * Internationalization (I18n) and (localization) * RSpec Test Helpers Configuration to ensure your Webpack bundles are ready for tests. * A supportive community. This web search shows how live public sites are using React on Rails. * Reason ML Support

Monthly Downloads: 81,279
Programming language: Ruby
License: MIT License
Tags: Web Frameworks     Web Apps     Web App Frameworks     React     Webpack     Node    
Latest version: v12.0.0-beta.1

ReactOnRails alternatives and similar gems

Based on the "Web Frameworks" category

Do you think we are missing an alternative of ReactOnRails or a related project?

Add another 'Web Frameworks' Gem



[License](./LICENSE.md) Build Status Gem Version npm version Code Climate Coverage Status

These are the docs for React on Rails 12, coming soon. To see the version 11 docs, click here.


June 12, 2020:

  1. Gem version: 12.0.0.pre.beta.0 and npm version 12.0.0-beta.0 released! Please try this out! Major enhancements:
    1. Typescript bindings
    2. Proper support for React Hooks
    3. i18n support for generating a JSON file rather than a JS file.
  2. See Justin's RailsConf talk: Webpacker, It-Just-Works, But How?.

April 2, 2020:

  • Are you interested in support for React on Rails? If so check out React on Rails Pro.
  • HMR is working with Loadable Components for a both amazing hot-reloading developer experience and great runtime performance. Please email me if you'd like to use Loadable Components Code Splitting to speed up your app by reducing your bundle sizes and lazily loading the code that's needed.
  • react_on_rails fully supports rails/webpacker. The example test app in spec/dummy was recently converted over to use rails/webpacker v4. It's a good example of how to leverage rails/webpacker's webpack configuration.


React on Rails integrates Rails with (server rendering of) Facebook's React front-end framework.

This project is sponsored by the software consulting firm ShakaCode. We focus on React front-ends, often with Ruby on Rails or Gatsby. The best way to see what we do is to see the details of our recent work.

Interested in optimizing your webpack setup for React on Rails including code splitting with react-router v4, webpack v4, and react-loadable with server side rendering? We just did this for Popmenu, lowering Heroku costs 20-25% while getting a 73% decrease in average response times.

Feel free to contact Justin Gordon, justin@shakacode.com, maintainer of React on Rails, for more information.

Click to join React + Rails Slack.


Project Objective

To provide an opinionated and optimal framework for integrating Ruby on Rails with React via the Webpacker gem especially in regards to React Server Rendering.

Features and Why React on Rails?

Given that rails/webpacker gem already provides basic React integration, why would you use "React on Rails"?

  1. Server rendering, often used for SEO crawler indexing and UX performance, is not offered by rails/webpacker.
  2. The easy passing of props directly from your Rails view to your React components rather than having your Rails view load and then make a separate request to your API.
  3. Redux and React Router integration with server-side-rendering.
  4. Internationalization (I18n) and (localization)
  5. [RSpec Test Helpers Configuration](docs/basics/rspec-configuration.md) to ensure your Webpack bundles are ready for tests. (and for [Minitest](docs/basics/minitest-configuration.md)).
  6. A supportive community. This web search shows how live public sites are using React on Rails.
  7. Reason ML Support.

See the react-webpack-rails-tutorial for an example of a live implementation and code.

ShakaCode Forum Premium Content

Requires creating a free account.


Consider browsing this on our documentation Gitbook.


React on Rails supports older versions of Rails back to 3.x. Rails/webpacker requires version 4.2+.

Getting Started

Note, the best way to understand how to use ReactOnRails is to study a few simple examples. You can do a quick demo setup, either on your existing app or on a new Rails app.

  1. Do the quick [tutorial](docs/tutorial.md).
  2. Add React on Rails to an existing Rails app per [the instructions](docs/basics/installation-into-an-existing-rails-app.md).
  3. Look at [spec/dummy](spec/dummy), a simple, no DB example.
  4. Look at github.com/shakacode/react-webpack-rails-tutorial; it's a full-featured example live at www.reactrails.com.

Basic Installation

See also [the instructions for installing into an existing Rails app](docs/basics/installation-into-an-existing-rails-app.md).

  1. Create a new Rails app:
   $ rails new my-app --webpack=react
   $ cd my-app
  1. Add the react_on_rails gem to Gemfile:
   gem 'react_on_rails', '11.1.4' # Use the exact gem version to match npm version
  1. Install the react_on_rails gem:
   $ bundle install
  1. Commit this to git (or else you cannot run the generator unless you pass the option --ignore-warnings).

  2. Run the generator:

   $ rails generate react_on_rails:install
  1. Start the app:
   $ rails s
  1. Visit http://localhost:3000/hello_world.

Turning on server rendering

With the code from running the React on Rails generator above:

  1. Edit app/views/hello_world/index.html.erb and set prerender to true.
  2. Refresh the page.

Below is the line where you turn server rendering on by setting prerender to true:

<%= react_component("HelloWorld", props: @hello_world_props, prerender: false) %>

Basic Usage


  • Configure config/initializers/react_on_rails.rb. You can adjust some necessary settings and defaults. See file [docs/basics/configuration.md](docs/basics/configuration.md) for documentation of all configuration options.
  • Configure config/webpacker.yml. If you used the generator and the default webpacker setup, you don't need to touch this file. If you are customizing your setup, then consult the [spec/dummy/config/webpacker.yml](./spec/dummy/config/webpacker.yml) example
    • Set compile: false for all envs
    • Your public_output_path must match your Webpack configuration for output of your bundles.
    • Only set cache_manifest to true in your production env.

Including your React Component on your Rails Views

  • React component are rendered via your Rails Views. Here's an ERB sample:
  <%= react_component("HelloWorld", props: @some_props) %>
  • Server-Side Rendering: Your react component is first rendered into HTML on the server. Use the prerender option:
  <%= react_component("HelloWorld", props: @some_props, prerender: true) %>
  • The component_name parameter is a string matching the name you used to expose your React component globally. So, in the above examples, if you had a React component named "HelloWorld", you would register it with the following lines:
  import ReactOnRails from 'react-on-rails';
  import HelloWorld from './HelloWorld';
  ReactOnRails.register({ HelloWorld });

Exposing your component in this way is how React on Rails is able to reference your component from a Rails view. You can expose as many components as you like, as long as their names do not collide. See below for the details of how you expose your components via the react_on_rails webpack configuration.

  • @some_props can be either a hash or JSON string. This is an optional argument assuming you do not need to pass any options (if you want to pass options, such as prerender: true, but you do not want to pass any properties, simply pass an empty hash {}). This will make the data available in your component:
    # Rails View
    <%= react_component("HelloWorld", props: { name: "Stranger" }) %>
  • This is what your HelloWorld.js file might contain. The railsContext is always available for any parameters that you always want available for your React components. It has nothing to do with the concept of the React Context. See [render functions and the RailsContext](docs/basics/render-functions-and-railscontext.md) for more details on this topic.
  import React from 'react';

  export default (props, railsContext) => {
    // Note wrap in a function to make this a React function component
    return () => (
        Your locale is {railsContext.i18nLocale}.<br/>
        Hello, {props.name}!

See the [View Helpers API](./docs/api/view-helpers-api.md) for more details on react_component and its sibling function react_component_hash.

Fragment Caching

Fragment caching is a React on Rails Pro feature. Fragment caching is a HUGE performance booster for your apps. Use the cached_react_component and cached_react_component_hash. The API is the same as react_component and react_component_hash, but for 2 differences:

  1. The cache_key takes the same parameters as any Rails cache view helper.
  2. The props are passed via a block so that evaluation of the props is not done unless the cache is broken. Suppose you put your props calculation into some method called some_slow_method_that_returns_props:
<%= cached_react_component("App", cache_key: [@user, @post], prerender: true) do
end %>

Such fragment caching saves a ton of CPU work for your web server and greatly reduces the request time. It completely skips the evaluation costs of:

  1. Database calls to compute the props.
  2. Serialization the props values hash into a JSON string for evaluating JavaScript to server render.
  3. Costs associated with evaluating JavaScript from your Ruby code.
  4. Creating the HTML string containing the props and the server-rendered JavaScript code.

Note, even without server rendering (without step 3 above), fragment caching is still effective.

Integration with Node.js for Server Rendering

Default server rendering is done by ExecJS. If you want to use a Node.js server for better performing server rendering, email justin@shakacode.com. ShakaCode has built a premium Node rendering server that is part of React on Rails Pro.

Globally Exposing Your React Components

For the React on Rails view helper react_component to use your React components, you will have to register them in your JavaScript code.

Use modules just as you would when using Webpack and React without Rails. The difference is that instead of mounting React components directly to an element using React.render, you register your components to ReactOnRails and then mount them with helpers inside of your Rails views.

This is how to expose a component to the react_component view helper.

  // app/javascript/packs/hello-world-bundle.js
  import HelloWorld from '../components/HelloWorld';
  import ReactOnRails from 'react-on-rails';
  ReactOnRails.register({ HelloWorld });

Different Server-Side Rendering Code (and a Server-Specific Bundle)

You may want different code for your server-rendered components running server side versus client side. For example, if you have an animation that runs when a component is displayed, you might need to turn that off when server rendering. One way to handle this is conditional code like if (window) { doClientOnlyCode() }.

Another way is to use a separate webpack configuration file that can use a different server side entry file, like 'serverRegistration.js' as opposed to 'clientRegistration.js.' That would set up different code for server rendering.

For details on techniques to use different code for client and server rendering, see: How to use different versions of a file for client and server rendering. (Requires creating a free account.)

Specifying Your React Components: Register directly or use render-functions

You have two ways to specify your React components. You can either register the React component (either function or class component) directly, or you can create a function that returns a React component, which we using the name of a "render-function". Creating a render-function allows:

  1. You have access to the railsContext. See documentation for the railsContext in terms of why you might need it. You need a render function to access the railsContext.
  2. You can use the passed-in props to initialize a redux store or set up react-router.
  3. You can return different components depending on what's in the props.

Note, the return value of a render function should be either a React Function or Class Component, or an object representing server rendering results.

Do not return a React Element (JSX).

ReactOnRails will automatically detect a registered render function by the fact that the function takes more than 1 parameter. In other words, if you want the ability to provide a function that returns the React component, then you need to specify at least a second parameter. This is the railsContext. If you're not using this parameter, declare your function with the unused param:

const MyComponentGenerator = (props, _railsContext) => {
  if (props.print) {
    // This is a React FunctionComponent because it is wrapped in a function.
    return () => <H1>{JSON.stringify(props)}</H1>;

Thus, there is no difference between registering a React function or class Component versus a "render function."

react_component_hash for render functions

Another reason to use a render function is that sometimes in server rendering, specifically with React Router, you need to return the result of calling ReactDOMServer.renderToString(element). You can do this by returning an object with the following shape: { renderedHtml, redirectLocation, error }. Make sure you use this function with react_component_hash.

For server rendering, if you wish to return multiple HTML strings from a render function, you may return an Object from your render function with a single top-level property of renderedHtml. Inside this Object, place a key called componentHtml, along with any other needed keys. An example scenario of this is when you are using side effects libraries like React Helmet. Your Ruby code will get this Object as a Hash containing keys componentHtml and any other custom keys that you added:

{ renderedHtml: { componentHtml, customKey1, customKey2} }

For details on using react_component_hash with react-helmet, see the docs below for the helper API and [docs/additional-reading/react-helmet.md](docs/additional-reading/react-helmet.md).

Error Handling

  • All errors from ReactOnRails will be of type ReactOnRails::Error.
  • Prerendering (server rendering) errors get context information for HoneyBadger and Sentry for easier debugging.


React on Rails provides an option for automatic conversions of Rails *.yml locale files into *.json or `.js. See the [How to add I18n](docs/basics/i18n.md) for a summary of adding I18n.

More Details

Browse the links in the [Summary Table of Contents](./SUMMARY.md)

Here are some highly recommended next articles to read:

  1. [How React on Rails Works](docs/outdated/how-react-on-rails-works.md)
  2. [Recommended Project Structure](./docs/basics/recommended-project-structure.md)
  3. [Webpack Configuration](./docs/basics/webpack-configuration.md)
  4. [View Helpers API](./docs/api/view-helpers-api.md)
  5. Caching and Performance: React on Rails Pro.
  6. [Deployment](docs/basics/deployment.md).


Click to join React + Rails Slack.

Community Resources

Please click to subscribe to keep in touch with Justin Gordon and ShakaCode. I intend to send announcements of new releases of React on Rails and of our latest blog articles and tutorials.


  • Slack Room: Contact us for an invite to the ShakaCode Slack room! Let us know if you want to contribute.
  • forum.shakacode.com: Post your questions
  • @railsonmaui on Twitter
  • For a live, open source, example of this gem, see www.reactrails.com.
  • See [Projects](PROJECTS.md) using and [KUDOS](./KUDOS.md) for React on Rails. Please submit yours! Please edit either page or email us and we'll add your info. We also love stars as it helps us attract new users and contributors.
  • See [NEWS.md](NEWS.md) for more notes over time.


Bug reports and pull requests are welcome. See [Contributing](CONTRIBUTING.md) to get started, and the list of help wanted issues.

React on Rails Pro

React on Rails Pro provides Node server rendering, fragment caching, code-splitting, and other performance enhancements for React on Rails. For a case study, see the article HVMN’s 90% Reduction in Server Response Time from React on Rails Pro. The Wiki contains more details.


React on Rails Pro Support

The React on Rails Pro Support Plan can help!

  • Optimizing your webpack setup to Webpack v4 for React on Rails including code splitting with react-router v4, webpack v4, and react-loadable.
  • Upgrading your app to use the current Webpack setup that skips the Sprockets asset pipeline.
  • Better performance client and server side.
  • Best practices based on over four years of React on Rails experience.
  • Using Reason with (or without) React on Rails.

ShakaCode can also help you with your custom software development needs. We specialize in marketplace and e-commerce applications that utilize both Rails and React. Because we own HawaiiChee.com, we can leverage that code for your app!

Please email Justin Gordon justin@shakacode.com, the maintainer of React on Rails, for more information.

Testimonials for ShakaCode

[HVMN Testimonial, by Paul Benigeri, October 12, 2018](./docs/testimonials/hvmn.md)

The price we paid for the consultation + the React on Rails pro license has already been made back a couple of times from hosting fees alone. The entire process was super hands off, and our core team was able to focus on shipping new feature during that sprint.

[ResortPass Testimonial, by Leora Juster, December 10, 2018](./docs/testimonials/resortpass.md)

Justin and his team were instrumental in assisting us in setting design foundations and standards for our transition to a react on rails application. Just three months of work with the team at Shaka code and we have a main page of our application server-side rendering at exponentially improved speeds.

From Joel Hooks, Co-Founder, Chief Nerd at egghead.io, January 30, 2017:


For more testimonials, see [Live Projects](PROJECTS.md) and [Kudos](./KUDOS.md).


The following companies support this open source project, and ShakaCode uses their products! Justin writes React on Rails on RubyMine. We use Scout to monitor the live performance of HawaiiChee.com, BrowserStack to solve problems with oddball browsers, and CodersRank to find candidates for our team.

2019-09-24_17-48-00 Scout BrowserStack CodersRank


I've just moved ShakaCode's development to ClubHouse from Trello. We're going to be doing this with all our projects. If you want to try ClubHouse and get 2 months free beyond the 14-day trial period, click here to use ShakaCode's referral code. We're participating in their awesome triple-sided referral program, which you can read about here. By using our referral code you'll be supporting ShakaCode and, thus, React on Rails!

If you'd like to support React on Rails and have your company listed here, get in touch.

Aloha and best wishes from Justin and the ShakaCode team!

Work with Us

ShakaCode is currently looking to hire like-minded, remote-first, developers that wish to work on our projects, including Hawaii Chee. Your main coding interview will be pairing with us on our open source! We're also using ReasonML extensively!


The gem is available as open source under the terms of the [MIT License](LICENSE.md).

*Note that all licence references and agreements mentioned in the ReactOnRails README section above are relevant to that project's source code only.