Clue Mediator

Navigate using react-router-dom v6

๐Ÿ“…October 6, 2022
๐Ÿ—ReactJS

Today weโ€™ll show you how to navigate in React application using react-router-dom v6. When dealing with the react-router-dom v6, it differs from the routing v5.

Refer to the following article if you are using react-router-dom v5.
Navigate from one page to another page in ReactJS

Ways to navigate using react-router-dom v6

  1. Link
  2. NavLink
  3. Navigate Component
  4. Navigating Programmatically

1. Link

The `Link` served as an anchor tag and is used to control the navigation. For a demonstration, see the code below.

import { Link } from 'react-router-dom';
...
...
<link to="/about">About

2. NavLink

The same functionality as `Link` is provided by `NavLink`, but it also allows us to show the link as the one the user is now viewing.

import { NavLink } from 'react-router-dom';
...
...
<navlink class="{({" isactive="" })=""> isActive ? 'active' : ''} to="/about">About</navlink>

3. Navigate Component

You can use the `<Navigate />` component to manage the redirection and use the `replace` attribute to overwrite the current location in the history stack.

import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
...
...
<browserrouter>
  <routes>
    <route path="/" element="{<Home">} />
    <route path="/about" element="{<About">} />
    <route path="*" element="{<Navigate" to="/" replace="">}
    />
  </route></route></route></routes>
</browserrouter>

4. Navigating Programmatically

If you want programmatically navigation from one page to another then you should use `useNavigate`. In other words, we can say if you want to manage the redirection on button click then you can use it.

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

export default function Login() {
  let navigate = useNavigate();

  return (
    <button onclick="{()" ==""> navigate("/dashboard")}
    >
      Login
    </button>
  );
}

Replace the current location

Use `replace` attribute to overwrite the location in history stack.

navigate('/dashboard', { replace: true });

Pass the value to another component

Refer to the following code to pass the value to another component using `useNavigate()`.

navigate("/dashboard", { state: { id: 1, data: {...} } });

Now use the `useLocation()` to read the state value.

import { useLocation } from "react-router-dom";
...
...
let location = useLocation();
console.log('Id: ', location.state.id);
console.log('Data: ', location.state.data);

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚