React Router in 8 Simple Steps

Jordan Panasewicz
3 min readFeb 2, 2021

--

If you’ve ever built a React app, chances are you’re familiar with React Router.

If you’re not, or need a refresher, React Router is basically what makes React so powerful in building single page web apps.

Through using React Router, we can manage the navigation of our web app, creating routes so that certain pages or ‘components’ appear when a user clicks on a link.

This is perfect for your header & footer as navigators for your website / web app.

Click here for the official documents.

Installation and Use

Follow these next few steps to get started with React Router after you’ve created a react app.

  1. Install react-router-dom:
npm install react-router-dom

2. In the Index.js file, import the Router:

import { BrowserRouter as Router } from "react-router-dom"

3. In the Index.js file, wrap the app component in the router:

The Router itself allows us to declare routes, switch between those routes, and set up links to navigate to each one of those routes. By wrapping the App in the Router, our entire App now has access to these declarations.

4. Navigate to the App.js file, and import Route, Switch, and Redirect:

import { Route, Switch, Redirect } from "react-router-dom"

5. In the App.js file, import a Header, as well as any other components you want to be able to navigate between:

Each import is a component, that will be used within our React Router ‘Switch’ as a Route to that specific page.

6. In the App.js file, render a Header above an open Switch. The Header should be OUTSIDE of the Switch. Within our Switch, create the routes to each of those pages by declaring the path (what get’s pulled from the url in a browser), and which component to load when that path gets called:

Each route acts as a means for the browser to pick up on the url path, and display the desired components to the user. For example: http://examplesite.com/write will now display the Write component.

7. Create (or navigate to) a Header.js file and import Link:

import { Link } from "react-router-dom"

8. In the Header.js file, declare your Links, and the path that each link will lead to:

Declare the path by using the “to” attribute for each Link.

Each Link in our header now has an associated route, and based on what Link the user clicks, they will only see the components associated with that route.

Creating powerful and quick single page web apps has never been easier.

Thank you for checking in, and I’ll see you again soon!

Cheers!

--

--

Jordan Panasewicz
Jordan Panasewicz

Written by Jordan Panasewicz

Denver, CO based. Software Sales turned Software Engineer.

Responses (1)