Rails with React — One Repo

Part 2 of 3: Integrating React Router

Harry Levine
Published in
2 min readNov 15, 2018

--

Recap

In part 1 of this series we covered setting React as the view layer.

All of the code for this series resides at: https://github.com/oddballio/rails-with-react

Introduction

As we now have the view layer staged, next we will want to be able to visit many different pages in our application, each with their own purpose. For example:

  • a home page
  • a page that displays a list of posts
  • a page with a form to create a new post

In order to create multiple React components with multiple, unique URLs, we will integrate React Router.

Create and import new components

Let’s create a class component to represent each of these pages, with some boilerplate content.

1. Create app/javascript/components/Home.js

2. Create app/javascript/components/Posts.js

3. Create app/javascript/components/NewPost.js

4. Import the components into App.js

Install and import dependencies

1. Install React Router and react-router-dom

$ yarn add react-router
$ yarn add react-router-dom

2. In index.js import the relevant package components

Setup the Router and Routes

Let’s integrate the components from these new packages.

1. In index.js, instead of passing in the App component, we’ll pass in the package’s Router component

2. Within the Router component, we’ll add a Route component that establishes a root path, with App.js as our root component

Create the routes in the React app

As App.js is set as the root component for the router, it will contain all of the individual routes for each component.

1. In App.js, import the Route and Switch components from react-router-dom

2. In App.js, establish all of the unique routes within a Switch component

Umbrella Rails route for all React routes

We need to create a catch all route that matches any of the potential routes that might come from our React app, and funnel them to our pages_controller#index action. This being the action that renders our React application.

Important: This match route must be the last route in routes.rb to ensure that it does not mistakenly absorb any other routes.

1. In routes.rb create the catch all route

2. Start the rails server with rails s

3. In a separate tab run the bin/webpack-dev-server script

$ bin/webpack-dev-server

This sets up the real time reloading that is standard with a basic React app.

4. Visit http://localhost:3000

You should see “Home page”

5. Visit http://localhost:3000/posts

You should see “Posts page”

6. Visit http://localhost:3000/new_post

You should see “NewPost page”

Next Steps

There is one more tutorial in this series:

Part 3 of 3: Handling Requests Between React and Rails

--

--