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.
Let’s start by installing React Router. We are going to be using the React Router v4, the newest version of React Router. React Router v4 can be used on the web and in native. So let’s install the one for the web.
Installing React Router v4
Run the following command in your working directory.
$ npm install react-router-dom --save
This installs the NPM package and adds the dependency to your package.json
.
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 code in src/index.js
with the following.
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
import "./index.css";
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById("root")
);
registerServiceWorker();
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.
If you liked this post, please subscribe to our newsletter, give us a star on GitHub, and check out our sponsors.
For help and discussion
Comments on this chapterFor reference, here is the code so far
Frontend Source :handle-routes-with-react-router