Rails with React - One Repo - Part 2
Harry Levine Nov 14
Part 2 of 3: Integrating React Router
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
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.
4. Import the components into
Install and import dependencies
$ yarn add react-router $ yarn add react-router-dom
index.js import the relevant package components
Setup the Router and Routes
Let's integrate the components from these new packages.
index.js, instead of passing in the
App component, we'll pass in the package's
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
App.js is set as the root component for the router, it will contain all of the individual routes for each component.
App.js, import the
Switch components from
App.js, establish all of the unique routes within a
Umbrella Rails route for all React routes
We need to create a catchall 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.
match route must be the last route in
routes.rb to ensure that it does not mistakenly absorb any other routes.
routes.rb create the catchall route
# config/routes.rb Rails.application.routes.draw do root 'pages#index' # IMPORTANT # # This `match` must be the *last* route in routes.rb match '*path', to: 'pages#index', via: :all end
2. Start the rails server with
3. In a separate tab run the
This sets up the real time reloading that is standard with a basic React app.
You should see "Home page"
You should see "Posts page"
You should see "NewPost page"
There is one more tutorial in this series: