In this article, we will learn how to use NavLink and useNavigate react js.
You can explore the application declaratively using the NavLink component.
It’s identical to the Link component, only it can apply an active style to the link if it’s active.
To specify the route to take, use the to prop and pass the path name.
The useNavigate() hook has replaced the useHistory() hook. In the previous version, the useHistory() hook visited the React Router history object and traversed to the other routers using the push and replace methods.
It allows you to navigate to a certain URL as well as forward and backward pages.
First you have to install react-router-dom using below command
npm i react-router-dom
Then create a router to link different pages, you can see below how to create routers in app.js
import { BrowserRouter, Routes, Route, Navigate, Outlet, useLocation, useNavigate } from "react-router-dom"; import Layout from "./components/usecontext2"; import Home from "./components/contextcom1"; function App() { return ( <BrowserRouter> <Routes> <Route exact path="/" element={<Layout />} /> <Route exact path="/home" index element={<Home />} /> </Routes> </BrowserRouter> ); } export default App;
Then, use Navlink and use navigator like this, you can see below
comp1
import React from "react"; export default function Contextcom1() { return ( <div>Home1</div> ) }
comp2
import React from "react"; import { NavLink, useNavigate } from "react-router-dom"; export default function Usecontext2() { const navigate = useNavigate(); return ( <> <NavLink to="/home">Home</NavLink> <button onClick={() => navigate("/home")}>Home</button> </> ) }
You can see below how it’s work