- Home
- Javascript
- Navigation with Link and NavLink
Navigation with Link and NavLink
Contents
Navigation with Link and NavLink
Why Not Use an Anchor Tag?
A regular <a href="/courses"> tells the browser to load a new page from the server. That reloads the entire application and loses all state — exactly what a single-page app is meant to avoid.
React Router provides <Link>, which changes the URL without reloading.
Example
src/components/Navbar.jsx
jsx
import { Link, NavLink } from "react-router-dom";
function Navbar() {
return (
<nav className="navbar">
<Link to="/" className="logo">GUVI Learn</Link>
<ul>
<li>
<NavLink
to="/"
className={({ isActive }) => isActive ? "nav-link active" : "nav-link"}
>
Home
</NavLink>
</li>
<li>
<NavLink
to="/courses"
className={({ isActive }) => isActive ? "nav-link active" : "nav-link"}
>
Courses
</NavLink>
</li>
<li>
<NavLink
to="/about"
className={({ isActive }) => isActive ? "nav-link active" : "nav-link"}
>
About
</NavLink>
</li>
</ul>
</nav>
);
}
export default Navbar;
How It Works
- <Link to="/courses"> replaces <a href>. Note the prop is to, not href.
- <NavLink> does the same but knows whether its route is currently active, which is how you highlight the current page in a navigation bar.
- className={({ isActive }) => ...} — NavLink accepts a function for className and passes in the active state.
Navigating from Code
Sometimes you need to redirect after an action, such as after a successful login. Use the useNavigate Hook:
jsx
import { useNavigate } from "react-router-dom";
function LoginForm() {
const navigate = useNavigate();
function handleSubmit(event) {
event.preventDefault();
// ...validate and log in...
navigate("/dashboard");
}
// ...
}
navigate(-1) goes back one step in history, the same as the browser back button.
ReactJS Tutorial
Vishalini A








