I’ll go demonstrate a very basic Rails + React project setup.
The code for the boilerplate React+Rails app is available here on Github
Make sure you have a fairly recent version of Ruby. To start off we need to fetch the latest and greatest Rails release. Luckily, there’s a very simple way of doing that. Rather than having to manually pick a version and/or messing with Gemfiles, all we need to do is
gem install rails --pre
Once that’s done, we’ll set up a new Rails project using the following. In this particular case we’ll skip over CoffeeScript and Turbolinks as we don’t have any use for them.
rails new test_app - dev - force --webpack --skip-coffee --skip-turbolinks
Yarn will be included too. Next thing we do is we’ll use Yarn to fetch the webpack-dev-server, like so
yarn add --dev webpack webpack-dev-server
Yarn will pull all the required packages and save the state in a lock file. Then we’ll install React using our local Rails binary and the new webpacker command-line tool.
then we run
This will automatically pull everything that’s needed to start using React. You’ll notice some new folders/files, among them the addition of webpack, webpack-dev-server and yarn inside of /bin as well as a host of other configuration files you’ll need to get to know in the future if you intend on using these features.
Now onto the Rails side of things. To consolidate Rails and React into one whole, we include it using the new webpack tag inside of our template (if youre’ doing this on an empty project, obviously you’ll want to do something like
rails g controller Main index
Inside of our template (index.html.erb or whatever it is), we add this
hello_react actually already exists – your project will have it – thanks to Webpack’s React generator. However, our Rails app is still at this moment unaware of there being a Webpack running and hosting the app. So what we’ll do now is head over to
and uncomment the third line
config.x.webpacker[:dev_server_host] = "http://localhost:8080"
This is basically it as far as setting up React w/ Rails goes these days (and likely in the future), however since this requires us to run two separate servers at the same time, we might want to make use of the almost indispensable foreman.
to your Gemfile, run
and create a file named
in your project’s root folder with the following content:
rails: bundle exec rails s
This way you’ll be able to run
with both the Rails and Webpack servers running inside of one tab. Granted, there are some downsides to it like debugging tools not working straight out of the box nor with all of their features available.
The boilerplate app is available over at https://github.com/kodius/boilerplate-react-rails