Handle Routes with React Router
Create React App sets a lot of things up by default but it does not come with a built-in way to handle routes. And since we are building a single page app, we are going to use React Router to handle them for us.
React Router allows us to specify a route like: /login
. And specify a React Component that should be loaded when a user goes to that page.
Let’s start by installing React Router.
Installing React Router
Run the following command in the frontend/
directory and not in your project root.
$ npm install react-router-dom@5.2.0 --save
This installs the NPM package and adds the dependency to the package.json
of your React app.
Setting up React Router
Even though we don’t have any routes set up in our app, we can get the basic structure up and running. Our app currently runs from the App
component in src/App.js
. We are going to be using this component as the container for our entire app. To do that we’ll encapsulate our App
component within a Router
.
Replace the following code in src/index.js
:
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
With this:
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById('root')
);
And import this in the header of src/index.js
.
import { BrowserRouter as Router } from 'react-router-dom';
We’ve made two small changes here.
- Use
BrowserRouter
as our router. This uses the browser’s History API to create real URLs. - Use the
Router
to render ourApp
component. This will allow us to create the routes we need inside ourApp
component.
Now if you head over to your browser, your app should load just like before. The only difference being that we are using React Router to serve out our pages.
Next we are going to look into how to organize the different pages of our app.
For help and discussion
Comments on this chapter