DEV Community

Cover image for A Really Simple Intro to React Router
Laura Todd
Laura Todd

Posted on

A Really Simple Intro to React Router

If you want to create a multi-page React app, the easiest way to navigate between pages is by using React Router. In this post I’ll take you through the steps of setting up a navbar for a simple app.

We’ll start off with three different components which will be three different pages in our app. You can call them whatever you like and put whatever content you like in each component. I’m going to call my components ‘Home’, ‘Products’ and ‘Contact’.

You can find the starting code here.

To begin, install React Router by typing ‘npm install react-router-dom’ in your terminal.
react-router-dom

Once it’s installed, go to your index.js file and import { BrowserRouter } from react-router-dom.

Add Browser Router

Then wrap the whole app with <BrowserRouter> tags so that that every component has access to React Router.
Wrap app in Browser Router

Next, go over to your App.js file and import { Route } and { Switch } from react-router-dom.

import Route and Switch

Now add a Route for each page of your app and wrap them with <Switch> tags. The path should be the url path for your page and the component property takes in the imported component. The exact property ensures that the route only works if the path used is exactly the same as the given path property.

Add routes for each page

Now let’s make our navbar by creating a new file called Navbar and adding a functional component as you would normally.

Add navbar component

Now import { Link } from react-router-dom.

Import Link

Add the links to the Navbar using . The to property should match the path you set up for each page in the App component.

Add Link tags

Finally, go back to the App.js file, import the Navbar component and add it to the App component.

import navbar component

That’s it! Now when you open your app, you’ll have a Navbar with links to each page.

You can check your final code here.

Top comments (0)