Navigate using react-router-dom v6
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
The Link
served as an anchor tag and is used to control the navigation. For a demonstration, see the code below.
1 2 3 4 | import { Link } from 'react-router-dom'; ... ... <Link to="/about">About</Link> |
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.
1 2 3 4 | import { NavLink } from 'react-router-dom'; ... ... <NavLink className={({ 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 />} /> </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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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.
1 | navigate('/dashboard', { replace: true }); |
Pass the value to another component
Refer to the following code to pass the value to another component using useNavigate()
.
1 | navigate("/dashboard", { state: { id: 1, data: {...} } }); |
Now use the useLocation()
to read the state value.
1 2 3 4 5 6 | 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..!! 🙂