How to install and use React Router

Carlos Hernandez
3 min readDec 27, 2020

What Is React Router?

React Router is a handy tool that allows our single page applications to function as if we have multiple pages for users to view. The benefit of this is giving users multiple page application functionality (different content per page) while retaining single page application website speed.

Project Startup

To start off this tutorial you will need to spin up a React App project using the npm package, ‘create-react-app’ so make sure you have it installed.

  • You can run “npm install -g create-react-app” to get the package!

Travel to your desired directory, mine was my desktop, and run the following command to create a project named ‘react-router-example’.

Once your app is created we will have to add the ‘react-router-dom’ package.

Implementing React Router

Now that we have React Router installed, we are able to utilize the package and its components to create Routes for our application. In your App.js file, add the following import statement:

The basic structure of using React Router is as follows:

  • The <Router> holds our <Switch> which then holds our apps <Routes>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}

A Route allows us to specify which component we wish to display when the inputted route matches the <Routes> ‘exact path’ value.

When a user visits my application’s empty route (“/”) or home route (“/home”) the HomePage component will be rendered on the DOM.

If a user visits my “dragon” route (“/dragon”) we will render the DragonPage components content.

Closing Notes

React Router provides much more functionality than this basic example, with React Router you are able to redirect users to other routes, gather variable values from route paths and much more. To explore all the possibilities visit React Router’s documentation at https://reactrouter.com/web/guides/quick-start. I hope this article helps you get started with creating something great!

View the example project on Github: https://github.com/chowder350/react-router-example

--

--

Carlos Hernandez

Full stack software engineer with a passion for serving and developing others.