I'll go demonstrate a very basic Rails + React project setup.
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.
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 first).
Inside of our template (index.html.erb or whatever it is), we add this
helloreact actually already exists - your project _will actually 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 convenient and almost indispensable tool called foreman.
to your Gemfile, run
bundle and create a file named
Procfile in your project's root folder with the following content:
rails: bundle exec rails s webpack: ./bin/webpack-dev-server
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 availble over at https://github.com/kodius/boilerplate-react-railsCategory: Rails, React