Aloha from Justin Gordon and the ShakaCode Team! We need your help. Venture capital funding has slowed and, for the first time, my ShakaCode team is actively looking for our next project. If you like React on Rails, please consider contacting me if we could potentially help you in any way. I'm offering a free half hour project consultation, on anything from React on Rails to any aspect of web application development, including both consumer and enterprise products. You can read more about my background here. Whether you have a new project, or need help on an existing project, please email me directly at justin@shakacode.com. And thanks in advance for any referrals! Your support keeps this project going.
- Besides consulting on bigger projects, ShakaCode is doing Skype plus Slack/Github based coaching for "React on Rails". Click here for more information.
- See our article The React on Rails Doctrine and see slides on React on Rails.
- For a complete example, see the React Webpack Rails Tutorial Code along with the live example at www.reactrails.com.
- The generator of React on Rails does not setup CSS modules and hot reloading via the Rails server as is demonstrated in the shakacode/react-webpack-rails-tutorial. We do support this, but we don't generate the code. If you did generate a fresh app from react_on_rails and want to move to CSS Modules, then see PR 175: Babel 6 / CSS Modules / Rails hot reloading. Note, while there are probably fixes after this PR was accepted, this has the majority of the changes. See the tutorial for more information. For more information on how to setup hot reloading in a Rails app, see Hot Reloading of Assets For Rails Development.
- 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.
- On Twitter, follow @railsonmaui and @shakacode for updates on releases.
- 2016-06-06: 6.0.2 shipped with a critical fix if you are fragment caching the server generated React.
- See NEWS.md for more notes over time.
Project Objective: To provide an opinionated and optimal framework for integrating Ruby on Rails with modern JavaScript tooling and libraries, including Webpack, Babel, React, Redux, React-Router. This differs significantly from typical Rails. When considering what goes into react_on_rails, we ask ourselves, is the functionality related to the intersection of using Rails and with modern JavaScript? If so, then the functionality belongs right here. In other cases, we're releasing separate npm packages or Ruby gems. If you are interested in implementing React using traditional Rails architecture, see react-rails.
React on Rails integrates Facebook's React front-end framework with Rails. React v0.14.x and greater is supported, with server rendering. Redux and React-Router are supported as well, also with server rendering, using either execJS or a Node.js server. See the Rails on Maui blog post that started it all!
Please see Getting Started for how to set up your Rails project for React on Rails to understand how react_on_rails
can see your ReactComponents.
-
Normal Mode (React component will be rendered on client):
<%= react_component("HelloWorldApp", props: @some_props) %>
-
Server-Side Rendering (React component is first rendered into HTML on the server):
<%= react_component("HelloWorldApp", props: @some_props, prerender: true) %>
-
The
component_name
parameter is a string matching the name you used to globally expose your React component. So, in the above examples, if you had a React component named "HelloWorldApp," you would register it with the following lines:import ReactOnRails from 'react-on-rails'; import HelloWorldApp from './HelloWorldApp'; ReactOnRails.register({ HelloWorldApp });
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("HelloWorldApp", props: { name: "Stranger" }) %>
// inside your React component this.props.name // "Stranger"
- Features
- Why Webpack?
- Getting Started
- How it Works
- Integration with Node
- Additional Reading
- Contributing
- License
- Authors
- About ShakaCode
Like the react-rails gem, React on Rails is capable of server-side rendering with fragment caching and is compatible with turbolinks. Unlike react-rails, which depends heavily on sprockets and jquery-ujs, React on Rails uses webpack and does not depend on jQuery. While the initial setup is slightly more involved, it allows for advanced functionality such as:
See the react-webpack-rails-tutorial for an example of a live implementation and code.
Webpack is used to generate several JavaScript "bundles" for inclusion in application.js
or directly in your layout.
This usage of webpack fits neatly and simply into the existing Rails sprockets system and you can include React components on a Rails view with a simple helper.
Compare this to some alternative approaches for SPAs (Single Page Apps) that utilize Webpack and Rails. They will use a separate node server to distribute web pages, JavaScript assets, CSS, etc., and will still use Rails as an API server. A good example of this is our ShakaCode team member Alex's article Universal React with Rails: Part I.
We're definitely not doing that. With react_on_rails, webpack is mainly generating a nice JavaScript file for inclusion into application.js
. We're going to KISS. And that's all relative given how much there is to get right in an enterprise class web application.
- Add the following to your Gemfile and bundle install.
gem "react_on_rails", "~> 5"
-
Commit this to git (you cannot run the generator unless you do this).
-
See help for the generator:
rails generate react_on_rails:install --help
- Run the generator with a simple "Hello World" example (more options below):
rails generate react_on_rails:install
- Bundle and NPM install. Make sure you are on a recent version of node. Please use at least Node v5. Bundle is for adding execJs. You can remove that if you are sure you will not server render.
bundle && npm install
- Start your Rails server:
foreman start -f Procfile.dev
See the Installation Overview for a concise set summary of what's in a React on Rails installation.
Configure the config/initializers/react_on_rails.rb
. You can adjust some necessary settings and defaults. See file spec/dummy/config/initializers/react_on_rails.rb for a detailed example of configuration, including comments on the different values to configure.
All JavaScript in React On Rails is loaded from npm: react-on-rails. To manually install this (you did not use the generator), assuming you have a standard configuration, run this command:
cd client && npm i --saveDev react-on-rails
That will install the latest version and update your package.json.
The generator installs your webpack files in the client
folder. Foreman uses webpack to compile your code and output the bundled results to app/assets/webpack
, which are then loaded by sprockets. These generated bundle files have been added to your .gitignore
for your convenience.
Inside your Rails views, you can now use the react_component
helper method provided by React on Rails. You can pass props directly to the react component helper. You can also initialize a Redux store with view helper redux_store
so that the store can be shared amongst multiple React components. Your best bet is to scan the code inside of the /spec/dummy sample app.
In most cases, you should use the prerender: false
(default behavior) with the provided helper method to render the React component from your Rails views. In some cases, such as when SEO is vital or many users will not have JavaScript enabled, you can enable server-rendering by passing prerender: true
to your helper, or you can simply change the default in config/initializers/react_on_rails
.
Now the server will interpret your JavaScript using ExecJS and pass the resulting HTML to the client. We recommend using therubyracer as ExecJS's runtime. The generator will automatically add it to your Gemfile for you.
In the following screenshot you can see the 3 parts of React on Rails rendering:
- A hidden HTML div that contains the properties of the React component, such as the registered name and any props. A JavaScript function runs after the page loads to convert take this data and build initialize React components.
- The wrapper div
<div id="HelloWorld-react-component-0">
specifies the div where to place the React rendering. It encloses the server-rendered HTML for the React component - Additional JavaScript is placed to console log any messages, such as server rendering errors. Note, these server side logs can be configured to only be sent to the server logs.
Note: If server rendering is not used (prerender: false), then the major difference is that the HTML rendered for the React component only contains the outer div: <div id="HelloWorld-react-component-0"/>
. The first specification of the React component is just the same.
Each time you change your client code, you will need to re-generate the bundles (the webpack-created JavaScript files included in application.js). The included Foreman Procfile.dev
will take care of this for you by watching your JavaScript code files for changes. Simply run foreman start -f Procfile.dev
.
On Heroku deploys, the lib/assets.rake
file takes care of running webpack during deployment. If you have used the provided generator, these bundles will automatically be added to your .gitignore
in order to prevent extraneous noise from re-generated code in your pull requests. You will want to do this manually if you do not use the provided generator.
When you use a "generator function" to create react components or you used shared redux stores, you get 2 params passed to your function:
- Props that you pass in the view helper of either
react_component
orredux_store
- Rails contextual information, such as the current pathname. You can customize this in your config file.
This information (props
and railsContext
) should be the same regardless of either client or server side rendering.
While you could manually pass the railsContext
information in as "props", the rails_context
is a convenience because it's passed consistently to all invocations of generator functions.
So if you register your generator function MyAppComponent
, it will get called like:
reactComponent = MyAppComponent(props, railsContext);
and for a store:
reduxStore = MyReduxStore(props, railsContext);
Note, you never make these calls. This is what React on Rails does when either server or client rendering. You'll be definining functions that take take these params and return a React component or a Redux Store.
(Note, see below section on how to setup redux stores that allow multiple components to talk to the same store.)
The railsContext
has: (see implementation in file react_on_rails_helper.rb for method rails_context for the definitive list).
{
# URL settings
href: request.original_url,
location: "#{uri.path}#{uri.query.present? ? "?#{uri.query}": ""}",
scheme: uri.scheme, # http
host: uri.host, # foo.com
port: uri.port,
pathname: uri.path, # /posts
search: uri.query, # id=30&limit=5
# Locale settings
i18nLocale: I18n.locale,
i18nDefaultLocale: I18n.default_locale,
httpAcceptLanguage: request.env["HTTP_ACCEPT_LANGUAGE"],
# Other
serverSide: boolean # Are we being called on the server or client? NOTE, if you conditionally
# render something different on the server than the client, then React will only show the
# server version!
}
Suppose you want to display a nav bar with the current navigation link highlighted by the URL. When you server render the code, you will need to know the current URL/path if that is what you want your logic to be based on. The new railsContext
has this information so the application of an "active" class can be done server side.
Suppose you want to server render your react components with localization applied given the current Rails locale. The railsContext
contains the I18n.locale.
Suppose you want to turn off animation when doing server side rendering. The serverSide
value is just what you need.
You can customize the values passed in the railsContext
in your config/initializers/react_on_rails.rb
. Here's how.
Set the config value for the rendering_extension
:
config.rendering_extension = RenderingExtension
Implement it like this above in the same file. Create a class method on the module called custom_context
that takes the view_context
for a param.
See spec/dummy/config/initializers/react_on_rails.rb for a detailed example.
module RenderingExtension
# Return a Hash that contains custom values from the view context that will get merged with
# the standard rails_context values and passed to all calls to generator functions used by the
# react_component and redux_store view helpers
def self.custom_context(view_context)
{
somethingUseful: view_context.session[:something_useful]
}
end
end
In this case, a prop and value for somethingUseful
will go into the railsContext passed to all react_component and redux_store calls. You may set any values available in the view rendering context.
Place your JavaScript code inside of the provided client/app
folder. Use modules just as you would when using webpack alone. The difference here is that instead of mounting React components directly to an element using React.render
, you expose your components globally and then mount them with helpers inside of your Rails views.
This is an example of how to expose a component to the react_component
view helper.
// client/app/bundles/HelloWorld/startup/HelloWorldApp.jsx
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 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!
If you do want different code to run, you'd setup a separate webpack compilation file and you'd specify a different, server side entry file. ex. 'serverHelloWorldApp.jsx'. Note, you might be initializing HelloWorld with version specialized for server rendering.
Once the bundled files have been generated in your app/assets/webpack
folder and you have exposed your components globally, you will want to run your code in your Rails views using the included helper method.
This is how you actually render the React components you exposed to window
inside of clientRegistration
(and global
inside of serverRegistration
if you are server rendering).
react_component(component_name,
props: {},
prerender: nil,
trace: nil,
replay_console: nil,
raise_on_prerender_error: nil,
id: nil,
html_options: {})
- component_name: Can be a React component, created using a ES6 class, or
React.createClass
, or a generator function that returns a React component. - options:
- props: Ruby Hash which contains the properties to pass to the react object, or a JSON string. If you pass a string, we'll escape it for you.
- prerender: enable server-side rendering of component. Set to false when debugging!
- id: Id for the div, will be used to attach the React component. This will get assigned automatically if you do not provide an id. Must be unique.
- html_options: Any other html options to get placed on the added div for the component.
- trace: set to true to print additional debugging information in the browser. Defaults to true for development, off otherwise. Note, on the client you will so both the railsContext and your props. On the server, you only see the railsContext being logged.
- replay_console: Default is true. False will disable echoing server-rendering logs to the browser. While this can make troubleshooting server rendering difficult, so long as you have the default configuration of logging_on_server set to true, you'll still see the errors on the server.
- raise_on_prerender_error: Default is false. True will throw an error on the server side rendering. Your controller will have to handle the error.
Include the module ReactOnRails::Controller in your controller, probably in ApplicationController. This will provide the following controller method, which you can call in your controller actions:
redux_store(store_name, props: {})
- store_name: A name for the store. You'll refer to this name in 2 places in your JavaScript:
- You'll call
ReactOnRails.registerStore({storeName})
in the same place that you register your components. - In your component definition, you'll call
ReactOnRails.getStore('storeName')
to get the hydrated Redux store to attach to your components.
- You'll call
- props: Named parameter
props
. ReactOnRails takes care of setting up the hydration of your store with props from the view.
For an example, see spec/dummy/app/controllers/pages_controller.rb.
redux_store_hydration_data
Place this view helper (no parameters) at the end of your shared layout. This tell ReactOnRails where to client render the redux store hydration data. Since we're going to be setting up the stores in the controllers, we need to know where on the view to put the client side rendering of this hydration data, which is a hidden div with a matching class that contains a data props. For an example, see spec/dummy/app/views/layouts/application.html.erb.
Note, you don't need to separately initialize your redux store. However, it's recommended for the two following use cases:
- You want to have multiple components that access the same store.
- You want to place the props to hydrate the client side stores at the very end of your HTML, so the browser can render all earlier HTML first. This is particularly useful if your props will be large.
Why would you create a function that returns a React component? For example, you may want the ability to use the passed-in props to initialize a redux store or setup react-router. Or you may want to return different components depending on what's in the props. ReactOnRails will automatically detect a registered generator function.
server_render_js(js_expression, options = {})
- js_expression, like 2 + 3, and not a block of js code. If you have more than one line that needs to be executed, wrap it in an IIFE. JS exceptions will be caught and console messages handled properly
- Currently the only option you may pass is
replay_console
(boolean)
This is a helper method that takes any JavaScript expression and returns the output from evaluating it. If you have more than one line that needs to be executed, wrap it in an IIFE. JS exceptions will be caught and console messages handled properly.
You may wish to have 2 React components share the same the Redux store. For example, if your navbar is a React component, you may want it to use the same store as your component in the main area of the page. You may even want multiple React components in the main area, which allows for greater modularity. In addition, you may want this to work with Turbolinks to minimize reloading the JavaScript. A good example of this would be something like an a notifications counter in a header. As each notifications is read in the body of the page, you would like to update the header. If both the header and body share the same Redux store, then this is trivial. Otherwise, we have to rely on other solutions, such as the header polling the server to see how many unread notifications exist.
Suppose the Redux store is called appStore
, and you have 3 React components that each need to connect to a store: NavbarApp
, CommentsApp
, and BlogsApp
. I named them with App
to indicate that they are the registered components.
You will need to make a function that can create the store you will be using for all components and register it via the registerStore
method. Note, this is a storeCreator, meaning that it is a function that takes (props, location) and returns a store:
function appStore(props, railsContext) {
// Create a hydrated redux store, using props and the railsContext (object with
// Rails contextual information).
return myAppStore;
}
ReactOnRails.registerStore({
appStore
});
When registering your component with React on Rails, you can get the store via ReactOnRails.getStore
:
// getStore will initialize the store if not already initialized, so creates or retrieves store
const appStore = ReactOnRails.getStore("appStore");
return (
<Provider store={appStore}>
<CommentsApp />
</Provider>
);
From your Rails view, you can use the provided helper redux_store(store_name, props)
to create a fresh version of the store (because it may already exist if you came from visiting a previous page). Note, for this example, since we're initializing this from the main layout, we're using a generic name of @react_props
. This means in this case that Rails controllers would set @react_props
to the properties to hydrate the Redux store.
app/views/layouts/application.html.erb
...
<%= redux_store("appStore", props: @react_props) %>;
<%= react_component("NavbarApp") %>
yield
...
Components are created as stateless function(al) components. Since you can pass in initial props via the helper redux_store
, you do not need to pass any props directly to the component. Instead, the component hydrates by connecting to the store.
_comments.html.erb
<%= react_component("CommentsApp") %>
_blogs.html.erb
<%= react_component("BlogsApp") %>
Note: You will not be doing any partial updates to the Redux store when loading a new page. When the page content loads, React on Rails will rehydrate a new version of the store with whatever props are placed on the page.
See ReactOnRails JavaScriptAPI.
React Router is supported, including server side rendering! See:
- React on Rails docs for react-router
- Examples in spec/dummy/app/views/react_router and follow to the JavaScript code in the spec/dummy/client/app/startup/ServerRouterApp.jsx.
- Version 6.0 puts the necessary precompile steps automatically in the rake precompile step. You can, however, disable this by setting certain values to nil in the config/react_on_rails.rb.
- See the Heroku Deployment doc for specifics regarding Heroku.
- If you're using the node server for server rendering, you may want to do your own AWS install. We'll have more docs on this in the future.
NodeJS can be used as the backend for server-side rendering instead of ExecJS. To do this you need to add a few files and then configure react_on_rails to use NodeJS. Here are the relevant files to add.
// client/node/package.json
{
"name": "react_on_rails_node",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./server.js -s webpack-bundle.js"
},
"dependencies": {
}
}
// client/node/server.js
var net = require('net');
var fs = require('fs');
var bundlePath = '../../app/assets/webpack/';
var bundleFileName = 'webpack-bundle.js';
var currentArg;
function Handler() {
this.queue = [];
this.initialized = false;
}
Handler.prototype.handle = function (connection) {
var callback = function () {
connection.setEncoding('utf8');
connection.on('data', (data)=> {
console.log('Processing request: ' + data);
var result = eval(data);
connection.write(result);
});
};
if (this.initialized) {
callback();
} else {
this.queue.push(callback);
}
};
Handler.prototype.initialize = function () {
console.log('Processing ' + this.queue.length + ' pending requests');
var callback;
while (callback = this.queue.pop()) {
callback();
}
this.initialized = true;
};
var handler = new Handler();
process.argv.forEach((val) => {
if (val[0] == '-') {
currentArg = val.slice(1);
return;
}
if (currentArg == 's') {
bundleFileName = val;
}
});
try {
fs.mkdirSync(bundlePath);
} catch (e) {
if (e.code != 'EEXIST') throw e;
}
fs.watchFile(bundlePath + bundleFileName, (curr) => {
if (curr && curr.blocks && curr.blocks > 0) {
if (handler.initialized) {
console.log('Reloading server bundle must be implemented by restarting the node process!');
return;
}
require(bundlePath + bundleFileName);
console.log('Loaded server bundle: ' + bundlePath + bundleFileName);
handler.initialize();
}
});
var unixServer = net.createServer(function (connection) {
handler.handle(connection);
});
unixServer.listen('node.sock');
process.on('SIGINT', () => {
unixServer.close();
process.exit();
});
The last thing you'll need to do is change the server_render_method to "NodeJS".
# app/config/initializers/react_on_rails.rb
config.server_render_method = "NodeJS"
- JavaScript API
- Ruby API
- Setting up Hot Reloading during Rails Development, API docs
- React on Rails, Slides
- The React on Rails Doctrine
- Installation Overview
- Migration from react-rails
- Babel
- Heroku Deployment
- Manual Installation
- Hot Reloading of Assets For Rails Development
- Node Dependencies and NPM
- React Router
- RSpec Configuration
- Server Rendering Tips
- Rails View Rendering from Inline JavaScript
- Tips
- Tutorial for v2.0, deployed here.
- Turbolinks
- Webpack Configuration
- Webpack Cookbook
- Changelog
- Projects
- Developing with the Webpack Dev Server
- www.reactrails.com with the source at shakacode/react-webpack-rails-tutorial.
- spec app: Great simple examples used for our tests.
cd spec/dummy bundle && npm i foreman start
- Ruby 2.1 or greater
- Rails 3.2 or greater
- Node 5.5 or greater
Bug reports and pull requests are welcome. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to our version of the Contributor Covenant Code of Conduct).
See Contributing to get started.
The gem is available as open source under the terms of the MIT License.
The origins of the project began with the need to do a rich JavaScript interface for ShakaCode's client Madrone and the choice to use Webapck and Rails, as described in Fast Rich Client Rails Development With Webpack and the ES6 Transpiler.
The gem project started with Justin Gordon pairing with Samnang Chhun to figure out how to do server rendering with Webpack plus Rails. Alex Fedoseev then joined in. Rob Wise, Aaron Van Bokhoven, and Andy Wang did the bulk of the generators. Many others have contributed.
We owe much gratitude to the work of the react-rails gem.
About ShakaCode
Visit our forums!. We've got a category dedicated to react_on_rails.
If you're looking for consulting on a project using React and Rails, email us ([contact@shakacode.com](mailto: contact@shakacode.com))! You can also join our slack room for some free advice.
We're looking for great developers that want to work with Rails + React with a distributed, worldwide team, for our own products, client work, and open source. More info here.