Official Documentation Link: https://reactrouter.com/docs/en/v6/getting-started/overview
Firstly, you have to install react-router-dom
by using npm i react-router-dom
or yarn add react-router-dom
and the import the following.
import {BrowserRouter, Routes, Route} from "react-router-dom".
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 amongst which we can navigate. Then the layouts (for e.g. Navbar, Footer, etc.) are wrapped inside the BrowserRouter but outside the Routes tag because they are same for all pages or routes. Then all the components/elements inside the Routes tag are written as follows:
<Route element={Home} path="/" />
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
1. Creating routes in App.js
<BrowserRouter>
<Navbar/>
<Routes>
<Route element={<Home/>} path="/" />
<Route element={<AboutUs/>} path="/aboutUs" />
<Route element={<ContactUs/>} path="/contactUs" />
<Routes>
<Footer />
<BrowserRouter/>
2. Links in React
The apps built without react, uses anchor tag to create hyperlinks as shown below.
<a href="">Link text</a>
This method works in react but using anchor tags leads to whole page refresh, which is undesirable. Instead, only some part of the page which is needed to be updated should be changed. react-router-dom helps to achieve this type of routing. In react we use <Link to=""> </Link>
instead of <a href=""> </a>
. Note that href is replaced by to. In short, if the website uses same layouts such as navbar or footer, then only the body of the pages are re-rendered.
3. Redirecting in react-router-dom v6
There are two ways to redirect in react-router-dom v6. First you can redirect to any path from the routes page where all the routes are written and second one is you can redirect from any component/element.
- Redirecting from a path: First:
import {Navigate} from "react-router-dom"
You just have to add following code to the
<Router path="/redirect" element={<Navigate to="/" replace } />
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 <Routes />
(i.e. "/home", "/aboutUs", "contactUs") we made.
- Redirecting from a component/element:
This can be achieved by using
useNavigation
hook. First:
import {useNavigate} from "react-router-dom";
Then initialize the function by:
const navigate = useNavigate();
Then we can use this variable navigate to navigate or redirect to any path.
Now simply just write
navigate("/path")
This will navigate to "/path"
Top comments (0)