← Back to Chapters

React Router: Link, NavLink & Active Links

? React Router: Link, NavLink & Active Links

? Quick Overview

React Router provides Link and NavLink components to handle navigation in Single Page Applications without refreshing the page.

? Key Concepts

  • Link replaces traditional anchor tags
  • NavLink detects active routes automatically
  • Active routes improve UX with visual feedback

? Syntax & Theory

Use to instead of href. React Router intercepts navigation and renders components dynamically.

? Using <Link>

? View Code Example
// Basic navigation using Link component
import React from "react";
import { Link } from "react-router-dom";

function Navbar() {
return (

Home

About

Contact ); } export default Navbar;

? Using <NavLink>

? View Code Example
// NavLink applies active class automatically
import React from "react";
import { NavLink } from "react-router-dom";

function Navbar() {
return (
); } export default Navbar;

⚛️ React Router v6 Active Styling

? View Code Example
// Function-based className for active links
 isActive ? "active-link" : ""}
>
About

? Live Explanation

When the URL matches the route, NavLink applies the active class automatically using the isActive flag.

? Tips & Best Practices

  • Use Link for simple navigation
  • Use NavLink for menus and tabs
  • Never mix anchor tags with router links
  • Prefer conditional classes over inline styles

? Try It Yourself

  1. Create a navbar using NavLink
  2. Add a custom active style
  3. Test navigation without page reload
  4. Observe URL updates