Integration of React + Webpack + Rails + rails/webpacker including server-side rendering of React, enabling a better developer experience and faster client performance.
These are the docs for React on Rails 12. To see the version 11 docs, click here.
October 14, 2020: RUBY ROGUES RR 474: React on Rails V12 – Don’t Shave That Yak! with Justin Gordon.
October 1, 2020: See the spec/dummy example repo for a simple configuration of webpack via the rails/webpacker gem that supports SSR.
August 2, 2020: See the example repo of React on Rails Tutorial With SSR, HMR fast refresh, and TypeScript for a new way to setup the creation of your SSR bundle with
rails/webpacker.
July 8, 2020: Release v12 of React on Rails.
Major Improvements
Be sure to see the CHANGELOG.md and read the upgrade instructions: docs/basics/upgrading-react-on-rails.
React on Rails integrates Rails with (server rendering of) Facebook's React front-end framework.
This project is maintained by the software consulting firm ShakaCode. We focus on Ruby on Rails applications with React front-ends, often using TypeScript or ReasonML. We also build Gatsby sites. See our recent work for examples of what we do.
Interested in optimizing your webpack setup for React on Rails including code splitting with react-router, and loadable-components 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, [email protected], maintainer of React on Rails, for more information.
Click to join React + Rails Slack.
To provide a high performance framework for integrating Ruby on Rails with React via the Webpacker gem especially in regards to React Server-Side Rendering for better SEO and improved performance.
Given that
rails/webpackergem already provides basic React integration, why would you use "React on Rails"?
rails/webpacker.
See Rails/Webpacker React Integration Options for comparisons to other gems.
See the react-webpack-rails-tutorial for an example of a live implementation and code.
Requires creating a free account.
Consider browsing this on our website.
Ruby on Rails >=5 and rails/webpacker 4.2+.
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.
See also the instructions for installing into an existing Rails app.
react_on_railsgem to Gemfile:
bundle add react_on_rails --strict
Commit this to git (or else you cannot run the generator unless you pass the option
--ignore-warnings).
Run the generator:
rails generate react_on_rails:install
rails s
With the code from running the React on Rails generator above:
app/views/hello_world/index.html.erband set
prerenderto
true.
Below is the line where you turn server rendering on by setting
prerenderto true:
Note, if you got an error in your console regarding "ReferenceError: window is not defined", then you need to edit
config/webpacker.ymland set
hmr: falseand
inline: false. See rails/webpacker PR 2644 for a fix for this issue.
config/initializers/react_on_rails.rb. You can adjust some necessary settings and defaults. See file docs/basics/configuration.md for documentation of all configuration options.
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 example or the official default webpacker.yml.
compile: falsefor development if you know that you'll always be compiling with a watch process. Otherwise, every request will check if compilation is needed.
public_output_pathmust match your custom Webpack configuration for
outputof your bundles.
cache_manifestto
truein your production env.
component_nameparameter 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 reactonrails webpack configuration. You may call
ReactOnRails.registermany times.
@some_propscan 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
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}.); };
Hello, {props.name}!
See the View Helpers API for more details on
react_componentand its sibling function
react_component_hash.
For the React on Rails view helper
react_componentto 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_componentview helper.
// app/javascript/packs/hello-world-bundle.js import HelloWorld from '../components/HelloWorld'; import ReactOnRails from 'react-on-rails'; ReactOnRails.register({ HelloWorld });
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.)
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:
railsContext. See documentation for the railsContext in terms of why you might need it. You need a Render-Function to access the
railsContext.
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 () =>{JSON.stringify(props)}
; } }
Thus, there is no difference between registering a React Function Component or class Component versus a "Render-Function." Just call
ReactOnRails.register.
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 reactcomponenthash with react-helmet, see our react-helmet documentation.
React on Rails provides an option for automatic conversions of Rails
*.ymllocale files into
*.jsonor `.js. See the How to add I18n for a summary of adding I18n.
Browse the links in the Summary Table of Contents
Here are some highly recommended next articles to read:
Click to join React + Rails Slack.
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.
Bug reports and pull requests are welcome. See Contributing to get started, and the list of help wanted issues.
Support React on Rails Pro development by becoming a Github sponsor and get these benefits.
React on Rails Pro includes 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.
The React on Rails Pro Support Plan can help!
rails/webpackersetup that skips the Sprockets asset pipeline.
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 HiChee.com, we can leverage that code for your app!
Please email Justin Gordon [email protected], the maintainer of React on Rails, for more information.
Fragment caching is a React on Rails Pro feature. Fragment caching is a HUGE performance booster for your apps. Use the
cached_react_componentand
cached_react_component_hash. The API is the same as
react_componentand
react_component_hash, but for 2 differences:
cache_keytakes the same parameters as any Rails
cacheview helper.
some_slow_method_that_returns_props:
Such fragment caching saves CPU work for your web server and greatly reduces the request time. It completely skips the evaluation costs of:
Note, even without server rendering (without step 3 above), fragment caching is still effective.
Default server rendering is done by ExecJS. If you want to use a Node.js server for better performing server rendering, email [email protected]. ShakaCode has built a premium Node rendering server that is part of React on Rails Pro.
HVMN Testimonial, by Paul Benigeri, October 12, 2018
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
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 and Kudos.
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 HiChee.com, Rails AutoScale to scale the dynos of HiChee, BrowserStack to solve problems with oddball browsers, and CodersRank to find candidates for our team.
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!
ShakaCode is currently looking to hire like-minded, remote-first, developers that wish to work on our projects, including HiChee. 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.