Skip to content

M07 - React Router

Introduction

React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces. React Router runs anywhere React runs; on the web, on the server with node.js, and on React Native.

Installation

Use below command install React Router to your React application:

1
npm install react-router-dom

Basic use case

Use BrowserRouter in your index.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import * as React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

const root = ReactDOM.createRoot(
  document.getElementById("root")
);
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

And add Routes to your application different pages in App.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import * as React from "react";
import { Routes, Route, Link } from "react-router-dom";
import "./App.css";

function App() {
  return (
    <div className="App">
      <h1>Welcome to React Router!</h1>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="about" element={<About />} />
      </Routes>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
        </ul>
      </nav>
    </div>
  );
}

Route components can be defined inside your App.js or use separated files.

Home

1
2
3
4
5
6
7
8
function Home() {
  return (
    <div>
      <h2>Home</h2>
      <p>This is your application Home page.</p>
    </div>
  );
}

About

1
2
3
4
5
6
7
8
function About() {
  return (
    <div className="About">
      <h2>About</h2>
      <p>This is your application About page.</p>
    </div>
  );
}

Test your application and click About and Home links to change visible page. Note how web browser's URL location changes between http://localhost:3000/ and http://localhost:3000/about.

Image 01 Image 02

Note

You can use Link element to define links to another pages.

Router Hooks

React Router ships with a few hooks that let you access the state of the router and perform navigation from inside your components. You can access history, location and parameters via hooks with easy and elegant way.

useLocation

The useLocation hook returns the location object that represents the current URL.

Modify About function to show current location.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { useLocation } from "react-router-dom";

function About() {
  const { pathname } = useLocation();
  return (
    <div className="About">
      <h2>About</h2>
      <p>This is your application About page.</p>
      <p>Current URL: {pathname}</p> 
    </div>
  ); 
}

Image 03

useNavigate

The useNavigate hook returns a function that lets you navigate programmatically.

Modify About function to use useHistory hook.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import { useLocation, useNavigate } from "react-router-dom";

function About() {
  const { pathname } = useLocation();
  let navigate = useNavigate();
  return (
    <div className="About">
      <h2>About</h2>
      <p>This is your application About page.</p>
      <p>Current URL: {pathname}</p> 
      <button onClick={() => navigate('/') } >Go to home</button>
    </div>
  ); 
}

Save your project and it should render a Home page first. Click About link and it will render a Button element. Click it and you should see Home page again.

Image 04

useParams

useParams returns an object of key/value pairs of URL parameters.

1
import { useParams } from "react-router-dom";

Create a new User function. Find user name from the incoming parameters.

1
2
3
4
5
6
7
8
9
function User() {
  const { name } = useParams()
  return (
    <div className="User">
      <h2>User</h2>
      <p>Username is {name}.</p>
    </div>
  );
}

Modify your app routes to use User function in routes and pass hardcoded name to it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function App() {
  const name = "Kirsi Kernel"
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="about" element={<About />} />
        <Route path="/user/:name" element={<User />} />
      </Routes>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>          
          <li><Link to={`/user/${name}`}>User</Link></li>
        </ul>
      </nav>
    </div>
  );
}

Save your project and it should render a Home page first. Click User link and it will render a User page with the name.

Image 05

Example : products

This example will load products from https://dummyjson.com and store loaded products to Redux productsSlice. First all products will be shown with Products.js (this is a default route). Product details will be shown with Products.js when user clicks one of the products. This is done by changing the route of the application.

Files:

  • index.js configure Redux store and browser router
  • App.js define routes to products and product
  • Product.js show product details
  • Products.js show all products
  • productsSlice.js store products data

Read more