router

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.

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

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

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

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.

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

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

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

Finally, go back to the App.js file, import the Navbar component and add it to the App 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.

Leave a Reply

Your email address will not be published. Required fields are marked *