DEV Community

Sesughter01
Sesughter01

Posted on

Routing in Reactjs v 16 +

hello react people good day. Please can I get any help; like a reference to docs or vids where I can learn how routing and redirecting is done in the new versions of react?
I have tried searching the react documentation online but maybe I don't get how it works but it doesn't bring up anything I need when I type any of the words "routing" or "redirect"

Top comments (1)

Collapse
 
omkarghodake profile image
Omkar-Ghodake • Edited

Official Documentation Link: reactrouter.com/docs/en/v6/getting...

Firstly, you have to:

import {BrowserRouter, Routes, Route} from "react-router-dom".
Enter fullscreen mode Exit fullscreen mode

All the elements/components are wrapped in "BrowserRouter" tag. All the pages (for e.g. Home, About US, Contact Us, etc.) are then wrapped in "Routes" tag. They are going to be the routes in which we can navigate. Then the layouts (for e.g. Navbar, Footer, etc.) are wrapped inside the "BrowserRouter" but outside the "Routes" tag. Then all the components/elements inside the "Routes" tag are written as follows:

<Route element={Home} path="/" />
Enter fullscreen mode Exit fullscreen mode

Unlike react-router-dom v5, there is no need to specify exact path for the element.

Example Code:
Suppose, there are 3 pages: Home, AboutUs, ContactUs
and 2 layouts: Navbar, Footer

<BrowserRouter>
    <Navbar/>
    <Routes>
        <Route element={<Home/>} path="/" />
        <Route element={<AboutUs/>} path="/aboutUs" />
        <Route element={<ContactUs/>} path="/contactUs" />
    <Routes>
    <Footer />
<BrowserRouter/>
Enter fullscreen mode Exit fullscreen mode

There are two ways to redirect in react-router-dom v6. First you can redirect at any path and second one is you can redirect from any component/element.

  1. Redirecting from a path: First:
import {Navigate} from "react-router-dom"
Enter fullscreen mode Exit fullscreen mode

You just have to add following code to the

<Router path="/redirect" element={<Navigate to="/" replace } />
Enter fullscreen mode Exit fullscreen mode

In this case, when you'll hit the path "/redirect" it will automatically redirect to path "/". If you replace path (i.e. "/redirect") by "*", then any it will redirect to "/" on any path excluding the (i.e. "/home", "/aboutUs", "contactUs") we made.

  1. Redirecting from a component/element: This can be achieved by using useNavigation hook. First:
import {useNavigate} from "react-router-dom";
Enter fullscreen mode Exit fullscreen mode

Then initialize the function by:

const navigate = useNavigate();
Enter fullscreen mode Exit fullscreen mode

Then we can use this variable "navigate" to navigate/redirect to any path.
Now simply just write

navigate("/path")
Enter fullscreen mode Exit fullscreen mode

wherever you want to redirect to a certain path.