Basic Guide to use React Router v6

Single Page Applications in React require a means of routing to navigate on to different views without refreshing the webpage. This can be done using React Router.
If you don't know how router works in React, I suggest you read about it and then follow this guide to get updated with the latest version of it.
The v6 of React Router is still in beta mode. This Blog is going to give you a peek into some of the new features that the library is coming out with.

1. <BrowserRouter>

We first need to import <BrowserRouter>. It is an interface which is required to use React Router. Here we have used an alias Router which makes it easier to write. We import it in our index.js file and wrap it around our <App/>

import React from 'react';
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
    <Router>
      <App />
    </Router>,
  rootElement
);

Its syntax is much similar to that of context APIs. It means that the App Component and its children will now have access to the Router APIs.

2. <Routes> and <Route>

Routes is a new element and an upgrade from previous Switch Component. It includes features like relative routing and linking, automatic route ranking and so on.
A Route has two main props, path which is nothing but the URL path and element which is the component to be rendered when the current URL matches the path.
Below is an example where we have three Route

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/menu" element={<Menu />} />
  <Route path="/about" element={<About />} 
</Routes>

3. <Link> and <NavLink>

When we use a simple <a href="abc.com">Some Link</a> for navigating it leads to refreshing of the webpage. To avoid this React Router provides a Link element.
A Link is an element that lets the user navigate to another page by clicking or tapping on it.
It has a prop to where we provide the path to which it should navigate.

import React from 'react';
import { Link } from 'react-router-dom';

export function Navbar() {
  return (
    <nav>
      <Link to="/home"> Home </Link>
      <Link to="/about"> About </Link>
    </nav>
  )
}

Link and NavLink are very similar and the only difference is that Navlink knows whether or not it is active. This is useful when you want to apply a style to the link which is active.

import React from 'react';
import { NavLink } from 'react-router-dom';

export function Navbar() {
  return (
    <nav>
      <NavLink to="/home" activeStyle={{textDecoration:"underline" , color:"red"}}> Home </Link>
      <NavLink to="/about" activeStyle={{textDecoration:"underline" , color:"red"}}> About </Link>
    </nav>
  )
}

4. useNavigate hook

The useNavigate hook lets you navigate programmatically . This is useful any time you need to navigate imperatively, e.g. after the user submits a form or clicks on a button.

import React from 'react';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';

function App() {
  let navigate = useNavigate();
  let [error, setError] = React.useState(null);

  async function handleSubmit(event) {
    event.preventDefault();
    let result = await submitForm(event.target);
    if (result.error) {
      setError(result.error);
    } else {
      navigate('success');
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      // ...
    </form>
  );
}

5. useParams hook

The useParams hook is used to access the URL params. It is very useful in case you want to make an Individual ProductPage for products in an Ecommerce App.

<Route path="/products/:id" element={<ProductPage />} />

When used in a nested route it returns an object of all the params in the URL. Below is a simple implementation on how to use useParams to access the URL params.

import React from 'react';
import { useParams } from 'react-router-dom';
import { products } from './data/products';

export function ProductPage() {
  const { id } = useParams()
  const product = products.find(el => el.id === id)
  return (
     <li key={product.id}>
        <h3>{product.name}</h3>
        <p>{product.description}</p>
        <p>{product.price}</p>
     </li>
  );
}

I hope you learnt a lot from this blog. Now, you can try implementing the latest version of React Router in your projects. You can also check the docs for more information.

If you enjoyed this post, I’d be very grateful if you’d share it. Also, This is my first blog. I am open to any suggestions. Comment below if you have any doubts or questions.

Thank you for reading!

22