React on Rails integrates Rails with (server rendering of) Facebook's React front-end framework.
Intersted in optimizing your webpack setup for React on Rails including code splitting with react-router v4, webpack v4, and react-loadable? Contact me.
ShakaCode is currently looking to hire like-minded 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 getting into Reason!
To provide an opinionated and optimal framework for integrating Ruby on Rails with React via the Webpacker gem.
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
See the react-webpack-rails-tutorial for an example of a live implementation and code.
React on Rails Pro provides Node server rendering and other performance enhancements for React on Rails. It's live at egghead.io. See the React on Rails Pro Docs.
The React on Rails Pro Support Plan can help you with:
- 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.
- Efficiently migrating from Angular to React.
- Best practices based on four years of React on Rails experience.
ShakaCode can also help you with your Rails, JavaScript, and React-Native development needs. We build custom web and mobile applications. Because we own HawaiiChee.com, we can leverage that code for your app!
The article Why Hire ShakaCode? provides additional details about our projects.
Please email me (Justin Gordon), the creator of React on Rails, to see if I can help you or if you want an invite to our private Slack room for ShakaCode.
From Kyle Maune of Cooper Aerial, May 4, 2018
From Joel Hooks, Co-Founder, Chief Nerd at egghead.io, January 30, 2017:
For more testimonials, see Live Projects and Kudos.
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+.
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.
- Do the quick tutorial.
- Add React on Rails to an existing Rails app per the instructions.
- Look at spec/dummy, a simple, no DB example.
- Look at github.com/shakacode/react-webpack-rails-tutorial; it's a full featured example live at www.reactrails.com.
See also the instructions for installing into an existing Rails app.
-
Create a new Rails app:
$ rails new my-app --webpack=react $ cd my-app
-
Add the
react_on_rails
gem to Gemfile:gem 'react_on_rails', '11.0.9' # Use the exact gem version to match npm version
-
Install the
react_on_rails
gem:$ bundle install
-
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
-
Start the app:
$ rails s
With the code from running the React on Rails generator above:
- Edit
app/views/hello_world/index.html.erb
and setprerender
totrue
. - 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) %>
- Configure
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. - 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 example- Set
compile: false
for all envs - Your
public_output_path
must match your Webpack configuration foroutput
of your bundles. - Only set
cache_manifest
totrue
in your production env.
- Set
-
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 asprerender: 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 Generator Functions and the RailsContext for more details on this topic.
import React from 'react'; export default (props, railsContext) => { return ( <div> Your locale is {railsContext.i18nLocale}.<br/> Hello, {props.name}! </div> ); };
See the View Helpers API for more details on react_component
and its sibling function react_component_hash
.
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:
- The
cache_key
takes the same parameters as any Railscache
view helper. - 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
some_slow_method_that_returns_props
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:
- Database calls to compute the props.
- Serialization the props values hash into a JSON string for evaluating JavaScript to server render.
- Costs associated with evaluating JavaScript from your Ruby code.
- 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.
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.
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 });
You may want different initialization for your server-rendered components. For example, if you have an animation that runs when a component is displayed, you might need to turn that off when server rendering. However, the railsContext
will tell you if your JavaScript code is running client side or server side. So code that required a different server bundle previously may no longer require this. Note, checking if window
is defined has a similar effect.
If you want different code to run, you will set up a separate webpack compilation file and you will specify a different, server side entry file. ex. 'serverHelloWorld.jsx'. Note: you might be initializing HelloWorld with version specialized for server rendering.
You have two ways to specify your React components. You can either register the React component directly, or you can create a function that returns a React component. Creating a function has the following benefits:
- You have access to the
railsContext
. See documentation for the railsContext in terms of why you might need it. You need a generator function to access therailsContext
. - You can use the passed-in props to initialize a redux store or set up react-router.
- You can return different components depending on what's in the props.
ReactOnRails will automatically detect a registered generator function. Thus, there is no difference between registering a React Component versus a "generator function."
Another reason to use a generator 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 generator function, you may return an Object from your generator 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.
- All errors from ReactOnRails will be of type ReactOnRails::Error.
- Prerendering (server rendering) errors get context information for HoneyBadger and Sentry for easier debugging.
You can enable the i18n functionality with react-intl. React on Rails provides an option for automatic conversions of Rails *.yml
locale files into *.js
files for react-intl
. 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:
- How React on Rails Works
- Recommended Project Structure
- Webpack Configuration
- View Helpers API
- Caching and Performance: React on Rails Pro.
- Deployment.
Aloha, I'm Justin Gordon the creator and maintainer of React on Rails. I'm supporting my continued dedication to this project by project by offering a React on Rails Pro Support Plan. Please email me to see if I can help you.
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 using and KUDOS 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 for more notes over time.
Bug reports and pull requests are welcome. See Contributing to get started, and the list of help wanted issues.
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, and we use BrowserStack to solve problems with oddball browsers.
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!
The gem is available as open source under the terms of the MIT License.