A Step by Step Guide: React Router

Jahaira Marrero
4 min readMar 29, 2021

--

This guide will help you create a multi-page single page application.

The Setup

  1. Install React-Router-DOM by running ‘npm install react-router-dom’ in the terminal. This adds it as a dependency which gets installed with all of the react code.
  2. In the index.js file, import { BrowserRouter } from “react-router-dom” and wrap it around the entire App because you want your whole App to have access to this.

App.js

  1. In the App.js file, import { Switch, Route}. You need to establish the routes for the components.
  2. Decide which components you would like to have a route. In this case, I want ItemList, ItemDetail, and ItemForm to each have their own route. Notices:
  • Switch is written after the Header because I want the Header component to remain on the page at all times.
  • I’ve included the prop “exact” before the path because I want the component to render only if it’s written exactly like it. If not, the Switch feature causes the app to render the first component that closely matches the url, which may give you issues later on when rendering via an id.
  • The name of the path you will see in the address bar is what is typed after the forward slash in path.

Header.js

At this point we are only able to access the components by typing it in the address bare. We now need to start rendering the components.

  1. Import { NavLink } from react-router-dom and replace the anchor tags and href with NavLink or { Link }. The main difference between the two is that NavLink highlights the component’s button/link on the page. It’s more so for style. Note: This is only for internal links.

Linking objects to their id.

  1. Import { Link } from react-router-dom. Please note: I didn’t title this section the name of the component because this will vary with each app.
  2. Make sure you pass down the id of the object via props (this is usually done in a container component). This is very important, so if you haven’t passed it down, go back to where you are getting your prop from to make sure that id is included with the rest of the attributes.
  • In this instance, I created a const named ‘link’ and passed the object id. I then called the variable on the Link tag.

Currently, what this is doing is changing the url to match the id of the object that we want to render but it’s not actually rendering yet.

Rendering the object to the page.

In order to actually render the object on the page, we must use {useParams}.

  1. Import { useParams}.
  2. Create const params = useParams()
  3. Create const id = params.id

If you want to a link that takes you to the next item for sale then line 27 is a typical format. You would need to parseInt on the id then add 1 so it can go to the next object.

--

--

No responses yet