How to use React Router in your React js project.

Manish Mandal
How To React
Published in
6 min readOct 22, 2020

In this tutorial, we will learn how to use React router in our project. React router is one of the most popular library for React js. It’s used to create routes in our react application. So let us get started on how to use that in our React js project.

At the time of writing this tutorial, the react-router-dom is version 5.

  1. Let us start by creating a simple react project.
yarn create react-app yourprojectname

2. Now we will create some components. So go to your project src directory and create a directory with the name components and inside that directory create three files header.js, footer.js, about.js, and service.js. We will be using a functional component for this so create a functional component.

3. Now install react-router-dom in your project.

yarn add react-router-dom

Basic

1. Now open your index.js file and import BrowserRouter, Switch, and Route from react-router-dom.

import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

BrowserRouter: A <Router> that uses the HTML5 history API (pushState, replaceState and the popstate event) to keep your UI in sync with the URL.

Switch: Renders the first child <Route> or <Redirect> that matches the location.

Route: It’s responsible to render some UI when its path matches the current URL.

2. Now paste the below code in your index.js file.

Here I have imported all my components and created a Routing function to be called in ReactDOM render method. Inside the Routing function, the header footer component is called outside the Switch tag because it’s to be used on each page, and all our components are called inside the Switch tag under Route as a prop component. Inside Route, path denotes to the path you want to set for the component, and the exact prop is used when you have multiple paths that have similar names here /.

3. Now for navigating to our path we will create basic nav links from react-router. So just paste the below code in your header.js file.

4. Run your project and refresh the browser to see the changes.

useParams

useParams hook is used to retrieve the current path. This can be useful if you want to dynamically create your routes. Let see how to use that in our React project

  1. Create a paramChild.js file inside your component directory and paste the below code.

Here I have imported useParams hook from react-router-dom and created a simple functional component that will display the current path.

2. Now inside your index.js file paste the below code.

Here look at the Route of the ParamChild component I have just changed the path to /:id. Now if we run the application we will see the current path is getting printed.

useRouteMatch

useRouteMatch hook can be used to create a nested route in your react project. This can be used to create dynamic nested routes. Let see how to use that in our React project

  1. Create routeMatch.js file inside the components directory and paste the below code.

Here I am calling my useRouteMatch hook from react-router and Destructuring the path and url from that hook. After that, I am creating some navigation links which is creating the subpages of the current path. For example, if your path is http://localhost:3000/user the path from useRouteMatch will take that path and create another route with subpages in our case http://localhost:3000/user/info which is created using <Route path={`${path}/:userID`}> <ParamChild/> </Route>. I am calling ParamChild which we yet need to create.

2. Create a file with the name paramChild.js inside the components directory and paste the below code.

This is the same as the above example of paramChild just we are destructuring the userID and id from useParams hook.

3. Now paste this inside your index.js file and header.js file.

Note: The id we destructured from the useParam hook is declared in index.js file and the userID from the routeMatch.js file

useLocation

useLocation hook is used to get the search parameter or hash value of the link. This is useful in creating search functionality in your react project. If we console.log useLocation it gives us hash, pathname, search, and state.

Let see how to use that in our project

  1. Create useLocation.js file inside the components directory and paste the below code.

Here I am destructuring pathname, search and hash from the useLocation hook and displaying each one.

2. Now paste this inside the index.js file to call the component.

3. Now put this code in your header.js file to create some links. The first link contains the search parameter, the second contains the hash value, and the third one containing both search and hash values.

4. Now run the project to see changes.

useHistory

useHistory hook can be used to create a back button. It can be also useful to create a push button to push from a particular page to another page without reloading or using the Link tag. Let see how to use that in our React project.

  1. Create useHistory.js file inside the components directory and paste the below code.

Here I am just assigning the useHistory hook to the history variable and creating two simple buttons which onClick method will fire the history.push function and history.goBack function.

2. Now paste this inside the index.js file to call the component.

3. Now paste this in your header.js file and run the project.

The first button is redirecting the visitor to the previously visited page and the second button is redirecting to the page we specified. For the homepage, I have used / for any other page, you can use for example /user for the user page. There are some other methods too like goForward, location, createHref, etc which I’ll cover in another tutorial.

Redirect

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.

So this basically can be used to redirect to a new location. The most common examples of Redirect are…

<Route exact path="/">
{loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>

To redirect to a particular route if the user is logged in.

<Redirect to="/somewhere/else" />

Put this in a particular component and visiting that particular component will automatically redirect us to the Redirect location.

<Redirect
to={{
pathname: "/login",
search: "?utm=your+face",
state: { referrer: currentLocation }
}}
/>

This is useful when you want to redirect to a particular location with a search parameter and state. The search parameter and state then can be achieved from useLocation and useHistory hook.

Example: Just create a component inside the components directory and paste the below code. The index.js file and header file has similar steps we created above.

That’s it for today. Hope you will like this tutorial. Below I have shared the GitHub repository for reference. Each hooks tutorial are in separate directories so after cloning the repository go to each folder and then run yarn or npm install and npm start or yarn start

--

--

Manish Mandal
How To React

Full Stack Developer | React JS | Next JS | Node JS | Vue JS | Wordpress. Connect with me https://www.linkedin.com/in/manishmandal21/