The React Router

Jaskomal
4 min readApr 19, 2021

--

In this article I will talk about the React package that allows us to transform a single page web application into a multi view application. I will give brief overviews of some of the components of React Router BrowserRouter, Switch, Link, and NavLink. And cover two hooks that are used with React Router, useHistory and useParams.

So what exactly is the React Router and what does it do? React Router allows us to render a web app based on the url, so a user can navigate to whatever page they want to go to, instead of always starting from one set spot and having to go step by step to get their desired content. We wouldn’t want to build a ecommerce app where the user has to start from the home page and work their way to item they were just looking at every time they refresh. React Router makes websites dynamic so you can get a cleaner UI and not have all your web apps information showing up on one giant page.

To start we have to import BrowserRouter at the top of our application, after that we wrap our application in the <Router> component. Within <Router> we can put in our other components such as <Switch>, <Link>, and <Route>. Here the <Switch> component acts just like a if statement, and will render the first <Route> that matches the path. This makes the location of the paths important, because if you want to get a path that matches a certain id then you would have to put that path above a path with the same name, but without the id. One way to get around this is to include an exact in the <Route>, this way we don’t have to worry about the wrong component accidentally being displayed. The <Link> replaces the html tag <a> and has almost the same functionality one big difference is that the <a> tag makes the page reload whereas with the <Link> we get sent to the new url and the page doesn’t reload making it a faster transition since we don’t have to resend all the data the <a> tag would require. An example of this is shown below.

import React from 'react';
import {BrowserRouter, Switch, Route, Link} from 'react-router-dom';
function App() { return ( <Switch> <Route path='/home'>
<Home/>
</Route>
<Route path='/new'>
<News/>
</Route>
<Route path='/channels/:id'>
<Channel/>
</Route>
<Route exact path='/channels'>
<Channels/>
</Route>

</Switch>
)
}

Now we can go to components based on the url but what if we wanted to go back to where we just were? Retyping in the url would isn’t the best way to do this and would quickly become tedious. Luckily for us React Router has a hook called useHistory. A general way to think of this is that this hook gives us the back, forward buttons to navigate through our web app. From a technical viewpoint this is giving us an object and some of the more useful methods are the goBack, goForward, and the push. Now the goBack and goForward are exactly as they sound, they allow the user to navigate the browser. The push method allows you to change the url, an example of this would be a form. When the user pushes submit you can use .push to send the user to a new page showing that the information has been submitted. Heres an outline of how to setup the useHistory hook.

import {useHistory} from 'react-router-dom'function App() {
const history = useHistory()

function handleClick(){

fetch('https://localhost:3000/projects'),{
method: 'POST'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(),
})
.then(r) => r.json())
.then(data) => {
history.push('/home')
} } }}

The last hook I want to talk about is the useParams hook. This hook makes the url dynamic so when the user types in a specific url the content will change to match the request. And vice versa as well, so when the user hits submit on a web page the web app sends data and thus the url will be updated to match. An easy way to visual this is take Youtube as an example. On the homepage there are many videos, when you click on a video you get directed to the video that matches the id of what you clicked and the url will update to that video’s path. This is essentially how the useParams hook works.

import {useParams} from 'react-router-dom'function App() {        const params = useParams();        // and you would pass in to where ever you are sending your         
data to as fetch(`https://localhost3000/${id}`)

}

This is just a small sample of what the React Router hooks I have mostly used can do, there are still more hooks you can use that will make your app even more dynamic, such as useLocation, and useRouteMatch. These hooks, and React Router in general really makes it easier to create a functioning web app that has friendly UI, and is easy for a beginner programmer to follow along as well.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response