What's new in React Router V6

0

Hello React Devs, React Router has been updated to V6. It comes with new route parameters and with few changes. Now it is more simple and easy to use React router.

How to install React Router V6?

It's easy to install React Router V6. You have to just execute the below command to install React Router V6. You can also go to the official website to install and read about React Router.

for YARN

yarn add react-router-dom@6

for NPM

npm install react-router-dom@6

What is the first step after installing React Router V6?

After installing React Router, let's apply it to our react project. Next, we will import Routes and Router from react-router-dom. After that, we can use Routes and Router from react-router. Here Routes is a wrapper for Route. And Route as, you already know that the path of the address. import { Routes, Route } from "react-router-dom";

Here is a basic example for React Router V6.

import React from 'react'
import { BrowserRouter, Routes, Route } from "react-router-dom";

//components
import FormikValidation from './FormikValidation'
import ReactRouting from './ReactRouting';
import ReactSlick from './ReactSlick'


export default function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<ReactSlick />} />
                <Route path="/form" element={ <FormikValidation />} />
                <Route path="/reactRoute" element={<ReactRouting />} />
                <Route path='*' element={<h1 className="text-center my-5">Oops 404 Page Not Found</h1>} />
            </Routes>
        </BrowserRouter>
    )
}

Nested Routes in React Router V6.

In React Router V6, it's easy to create and use nested routing. It helps us to route sub routing.

Link and NavLink in React Router.

Link and NavLink help us to go on any URL link. Link and NavLink both work similarly. There is only one difference which, I found that Link is only used for navigating on any URL. On the other hand, NavLink also does the same. It also has an active attribute in NavLink. That helps us to show where the Link is active or not. It works the same as we do in a href in HTML.

Example for Link and NavLink

<Link exact to="/">Home Page </Link>
<NavLink exact activeClassName="active" to="/">Home Page </NavLink>

Add Active class in React Router.

Sometimes we need to show active and inactive indicate in links. That can help users to identify. You can also use the above example activeClassName in NavLink. Or you can also go through the below snippet. I would link to info you that active class only work with NavLink. You can't use the active class attribute with Link.

RouterNavbar File

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

export default function RouterNavbar() {
    return (
        <ul class="nav justify-content-center my-4">
            <li class="nav-item">
                <NavLink className={({ isActive }) => (isActive ? ' nav-link active text-warning' : 'nav-link text-dark')} aria-current="page" to="/first">
                    First Link
                </NavLink>
            </li>
            <li class="nav-item">
                <NavLink className={({ isActive }) => (isActive ? ' nav-link active text-warning' : 'nav-link text-dark')} aria-current="page" to="/second">
                    Second Link
                </NavLink>
            </li>
            <li class="nav-item">
                <NavLink className={({ isActive }) => (isActive ? ' nav-link active text-warning' : 'nav-link text-dark')} aria-current="page" to="/third">
                    Third Link
                </NavLink>
            </li>

        </ul>
    );
}

And I have also created three more files to show how routing work and How I am adding an active class in React Router.

<Route path="/first" element={<><RouterNavbar/><First/></>} />
                <Route path="/second" element={<><RouterNavbar/><Second/></>} />
                <Route path="/third" element={<><RouterNavbar/><Third/></>} />

import React from 'react';

export default function First() {
    return (
        <>
            <div className="container">
                <h1>First Route</h1>
                <p>lorem ipsum dolor sit amet lorem, consectetur adipis ac tur lorem. Ut en lorem. Ut lorem ipsum dolor sit</p>
            </div>
        </>
    );
}

On click on any link, it changes the route and also shows the yellow color for the active link.

URL redirect in React Router V6

For using redirect you need to import useNavigate from react-router-dom.

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

After function name you can define const Navigate = useNavigate(); Now you can use Navigate(routeName); for redirect

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

export default function ReactRouting() {

  const Navigate = useNavigate();

  useEffect(() => {
    Navigate('/first')
  }, [Navigate]);
  

  return (
    <>
      <h1>React Router</h1>
      <p>lorem ipsum dolor sit amet, consectetur adip</p>
    </>
  );
}

Passing props value through Navlink or Link in React Router v6.

<Link className="nav-item" to={"/first"} state={{ from: 'TypeHiddenValeHere' }} >Passing Value in first Page</Link>

We can also pass the state in NavLink using the same method. But after passing the value from the Link or NavLink. We also need to get state value on the page where the user has redirected to the click.

How to get props passed value using NavLink or Link in React Router v6?

For getting the value that is passed using props in Link. We need to import useLocation from the react-router-dom. Here I have a console log the values.

import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

export default function First(props) {
    const location = useLocation()

    useEffect(() => {
     console.log('getting location value', location)
     console.log('getting value passed from prop', location.state.from)
    }, []);
    


    return (
        <>
            <div className="container">
                <h1>First Route</h1>
                <p>lorem ipsum dolor sit amet lorem, consectetur adipis ac tur lorem. Ut en lorem. Ut lorem ipsum dolor sit</p>
            </div>
        </>
    );
}

Why do we need to pass the value in Link and NavLink using state from?

As we all know, if we pass the value from the get URL. Use can easily see the value and can change and process. It may be wrong entries in our database. On the other hand, it may take another action. Because most of the time, we pass value in the URL. And we check the condition from the URL link. If we pass value using state user can't see the value which we have the pass, also the user cannot change the value. It is the advantage of using state from in React Link and NavLink.

How to do Dynamic Routing in React Router v6?

In Dynamic routing, the page gets rendered through the route's data. In Dynamic routing, we also get conditional data to render the page, when the user gets there.

<Route path="/project:id" element={<projectView/>} />

Get the Params value in React Router.

For getting the params data, you need to import useParams from 'react-router-dom'. We use it to get the Dynamic Routing's value.

import React, { useEffect } from 'react';
import { useParams } from 'react-router-dom';

export default function First() {
    const params = useParams()

    useEffect(() => {
     console.log('getting params value', params)
    }, []);
    


    return (
        <>
            <div className="container">
                <h1>First Route</h1>
                <p>lorem ipsum dolor sit amet lorem, consectetur adipis ac tur lorem. Ut en lorem. Ut lorem ipsum dolor sit</p>
            </div>
        </>
    );
}

If you have any doubt, you can comment below. Thank

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !