React Router V6

React Router V6

A comprehensive guide for React Router V6

Hello Everyone, In this Article I'll try to explain basics of routing using React Router in React based applications.

What is Routing in React?

In React, Routing helps us to navigate between the different URL endpoints those make up our web application. Routes helps us to move between different components .

What is React Router ?

  • React Router is a collection of navigational components that used for navigation in React Apps.
  • React Router is the standard library for routing in React.
  • To use React Router in your project you have to install it first from npmjs npm i react-router

Components in React Router V6

1.BrowserRouter Component

  • BrowserRouter is one of the router that react-router provides us. We need to wrap our entire application inside the this router to use react-router functionality.

  • src/index.js

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>
);

In the above code I aliased the BrowserRouter as Router

Routes Component

In React-Router, Routes Component helps us to wrap multiple Route components

<Routes>
        <Route />
        <Route />
</Routes>

Route Component

In React-Router, Route Component takes majorly two props one is the path and other one is the element

path prop specifies the path where we need to render our component that we pass through element prop

for example below Route component is for the Home Route.

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

Output :

home-route

about-route

Here we are navigating to each route manually to navigate to them on a click we need to use <Link/> component

Link component is similar to our 'anchor' tag <a></a> and used to navigate between the endpoints

Link-Component

useParams Hook

useParams hook returns the key/value pairs of the dynamic params from the current URL that were matched by the path

In the below example i am passing id dynamically it can be captured by using useParams hook

<Routes>
          <Route path="/" element={<Home />} />
          <Route path="/books" element={<BookList />} />
          <Route path="/books/:id" element={<Book />} />
</Routes>

src/pages/BookList.jsx

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

export default function BookList() {
  return (
    <>
      <h1>Book List</h1>
      <Link to="/books/1">Book 1</Link>
      <Link to="/books/2">Book 2</Link>
    </>
  );
}

We can capture the dynamic id like in below code by using useParams Hook

import { useParams } from "react-router-dom";
export default function Book() {
  const { id } = useParams();
  return <>Book {id}</>;
}

Not Found

Lets say your searching for a endpoint that doesn't exists then we can render the proper Error page by using the * as the value for the path in the Route Component

src/pages/NotFound.jsx

export default function NotFound() {
  return <>Page Not Found :)</>;
}
<Route path="*"  element={<NotFound />}/>

Output: If you go to the endpoint in my case I went to pens endpoint in URL that doesn't exists I got below message

endpoint not found

Nested Routes

If we have common routes that are acting as the base route for many routes then we can nest them inside the common route let me show you what i am taking about in the below code.

<Routes>
          <Route path="/" element={<Home />} />
          <Route path="/books" element={<BookList />} />
          <Route path="/books/:id" element={<Book />} />
          <Route path="/books/new" element={<NewBook />} />
          <Route path="*" element={<NotFound />} />
</Routes>

In the above code we have books route as the basic route so we can nest the other routes which are having /books as the base route inside them like in the code below.

<Routes>
          <Route path="/" element={<Home />} />
          <Route path="/books">
            <Route index element={<BookList />} />
            <Route path=":id" element={<Book />} />
            <Route path="new" element={<NewBook />} />
            <Route />
          </Route>
          <Route path="*" element={<NotFound />} />
</Routes>

In the code above code I used index to render the component at the base route /books

Outlet Component

  • src/pages/BookLayout.jsx
import { Link, Outlet } from "react-router-dom";

export default function BookLayout() {
  return (
    <>
      <ul>
        <li>
          <Link to="/books/1">Book 1</Link>
        </li>
        <li>
          <Link to="/books/2">Book 2</Link>
        </li>
        <li>
          <Link to="/books/new">New Book</Link>
        </li>
      </ul>
      <Outlet />
    </>
  );
}
  • src/App.js
import { Link, Route, Routes } from "react-router-dom";
import Home from "./pages/Home";
import Book from "./pages/Book";
import BookList from "./pages/BookList";
import NotFound from "./pages/NotFound";
import NewBook from "./pages/NewBook";
import BookLayout from "./pages/BookLayout";
function App() {
  return (
    <>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/books">Books</Link>
          </li>
        </ul>
      </nav>
      <div>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/books" element={<BookLayout />}>
            <Route index element={<BookList />} />
            <Route path=":id" element={<Book />} />
            <Route path="new" element={<NewBook />} />
            <Route />
          </Route>
          <Route path="*" element={<NotFound />} />
        </Routes>
      </div>
    </>
  );
}
export default App;

<Outlet /> component helps us To render the content of the components inside the BookLayout.jsx and keeping the Links in the BookLayout.jsx in all the pages.

outlet-component

component helps us to highlight the currently clicked nav link it automatically adds active class to the currently clicked link below code shows the the thing.

  • src/App.js
    import { NavLink, Route, Routes } from "react-router-dom";
    import Home from "./pages/Home";
    import Book from "./pages/Book";
    import BookList from "./pages/BookList";
    import NotFound from "./pages/NotFound";
    import NewBook from "./pages/NewBook";
    import BookLayout from "./pages/BookLayout";
    function App() {
    const navStyle = ({ isActive }) => {
      return {
        fontWeight: isActive ? "bold" : "normal",
        textDecoration: isActive ? "none" : "underline",
      };
    };
    return (
      <>
        <nav>
          <ul>
            <li>
              <NavLink style={navStyle} to="/">
                Home
              </NavLink>
            </li>
            <li>
              <NavLink style={navStyle} to="/about">
                About
              </NavLink>
            </li>
            <li>
              <NavLink style={navStyle} to="/books">
                Books
              </NavLink>
            </li>
          </ul>
        </nav>
        <div>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/books" element={<BookLayout />}>
              <Route index element={<BookList />} />
              <Route path=":id" element={<Book />} />
              <Route path="new" element={<NewBook />} />
              <Route />
            </Route>
            <Route path="*" element={<NotFound />} />
          </Routes>
        </div>
      </>
    );
    }
    export default App;
    
    Output :

NavLink

Navigating Programmatically

In React Router we have useNavigate Hook that we can use to navigate on event for example click event below example code gives the idea where in on a click of button About Page it will navigate to About page.

src/App.jsx

import { useNavigate } from "react-router-dom";
export default function Home() {
  const navigate = useNavigate();
  return (
    <>
      <h1>Home</h1>
      <button onClick={() => navigate("about")}>About Page</button>
    </>
  );
}

output:

use-navigate-forward

We can go back to previous page by using the below code

src/About.jsx

import { useNavigate } from "react-router-dom";

export default function About() {
  const navigate = useNavigate();
  return (
    <>
      <h1>About</h1>
      <button onClick={() => navigate(-1)}>Go Back</button>
    </>
  );
}

output:

Go back

That's it for now. Thanks for reading