As you've probably guessed by the title of my article, I still consider Ruby on Rails as a relevant technology that offers a lot of value, especially when combined with ReactJS as it's frontend counterpart. Here's how I approach the topic.
Rails app is going to be treated as an API which communicates with the front-end side. Rails API leaves React to handle the UI.
In this article, we’re going to use webpacker gem to integrate Rails with React. However, there are other ways to create React applications. One of the most popular is to use create-react-app tool backed by Facebook. It provides a rich set of options and customizations.
Let’s get started. First, generate a new Rails app by running:
rails new app_name --webpack=react
One more thing worth the mention is that webpacker coexists with Rails asset pipeline. You still can serve things from there if you need to.
Let’s use the hello_react.js example right away and test our first React component.
rails g controller Home index
Set home#index as a root path to the routes file:
root to: 'home#index'
Use Webpacker helper method and add it to the head of the layout file:
To make our life easier and prevent us by running commands manually, we’re going to create Procfile.dev file in the root directory of our project. The file is going to be an instruction for a process manager to run processes simultaneously. In our case, it will run the rails server and webpack-dev-server.
We’re going to use Node Foreman so make sure you have it installed.
Fill the file with the following:
rails: bundle exec rails s webpack: ./bin/webpack-dev-server
foreman start -f Procfile.dev
If you need, you can run a single process as well by giving a process name at the end of the command for example:
foreman start -f Procfile.dev webpack
Great, we’re ready to start our server!
Hit http://localhost:3000/,and you should see “Hello React” rendered.