Configure the App to Use react-router

Learn to configure react-router in React applications.

This lesson covers the steps to configure and add react-router in a React application. It also introduces several types of routers that react-router provides.

Add react-router to a React app

In order to use react-router in the application, we need to connect it to the router element. To do this, we need to wrap the app or root element of the application inside the router element. This allows us to use the routing functionalities anywhere in the application. Before doing that, however, let’s review the router component.

What is the router component?

The router component is the core component of the react-router. Behind the scenes, it uses React Context to pass routing props to any component inside the application. In addition, the Router element subscribes to URL changes inside the browser and uses browser APIs, such as locations and history stacks to perform various tasks.

The react-router provides different routers based on where we’re running our apps.

  • BrowserRouter

This is used for running react-router in a web browser. It stores the current location in the browser’s address bar using URLs and navigates using its history stack. It keeps the UI in sync with the URL. We’ll use this router in this course.

  • HashRouter

This is used in the web browser when the URL can’t be sent to the server. It stores the current location in the hash portion of the URL like this:

Since the hash is never sent to the server, we don’t need any specific server configuration to handle this.

  • NativerRouter

It is used for running react-router in the React native apps.

  • MemoryRouter

This is used when we need complete control over the history stack for testing different routes.

  • StaticRouter

This is used when we’re using server-side rendering for our web application.

Add BrowserRouter to the current application

Once react-router is installed, we open the index.html file where the root component (App) is located and take the following steps to connect the router to the React application:

  1. Import BrowserRouter from react-router-dom

import { BrowserRouter } from 'react-router-dom';

  1. Add the App component as the child of the <BrowserRouter> component.
    <App />

Refer to the index.js file from the following code:

Get hands-on with 1200+ tech skills courses.