React Mastery / Routing (React Router)

Navigation in React Router

🌐 Client-Side Navigation (No Reload)

In React Router:

  • Navigation does not reload the page

  • Only the URL changes

  • React updates the UI instantly

❌ Traditional navigation (<a href="">)

  • Triggers full page reload

  • Loses state

βœ… React Router navigation

  • Fast

  • Smooth

  • SPA-friendly


πŸ”— What Is <Link>?

  • Used to navigate between routes

  • Replaces <a> tags in React apps

  • Prevents page reload

Example

<Link to="/">Home</Link>
<Link to="/contact">Contact</Link>

πŸ“Œ Always use Link for internal navigation.


🧭 What Is <NavLink>?

  • Special version of Link

  • Knows whether the route is active

  • Used for navigation menus

Basic Syntax

<NavLink to="/about">About</NavLink>

🎨 Active Link Styling

Using className Function

<NavLink
  to="/about"
  className={({ isActive }) =>
    isActive ? 'active-link' : 'link'
  }
>
  About
</NavLink>

Example CSS

.link {
  color: black;
  text-decoration: none;
}

.active-link {
  color: blue;
  font-weight: bold;
}

πŸ“Œ isActive becomes true when the route matches the URL.


πŸš€ What Is useNavigate()?

  • A hook used for programmatic navigation

  • Useful for:

    • Button clicks

    • Form submissions

    • Redirects after login

Basic Syntax

const navigate = useNavigate();
navigate('/dashboard');

Example: Button Navigation

import { useNavigate } from 'react-router-dom';

function LoginButton() {
  const navigate = useNavigate();

  return (
    <button onClick={() => navigate('/profile')}>
      Go to Profile
    </button>
  );
}

Go Back / Forward

navigate(-1); // back
navigate(1);  // forward

πŸ› οΈ Hands-On: Navbar with Active States

src/components/Navbar.jsx

import { NavLink } from 'react-router-dom';

function Navbar() {
  return (
    <nav>
      <NavLink to="/" end>Home</NavLink>
      <NavLink to="/about">About</NavLink>
      <NavLink to="/contact">Contact</NavLink>
    </nav>
  );
}

export default Navbar;

πŸ“Œ end ensures / matches only the home route.


πŸ”˜ Hands-On: Button-Based Navigation

import { useNavigate } from 'react-router-dom';

function ContactButton() {
  const navigate = useNavigate();

  return (
    <button onClick={() => navigate('/contact')}>
      Contact Us
    </button>
  );
}

export default ContactButton;

🧠 Common Mistakes

  • ❌ Using <a href> instead of Link

  • ❌ Forgetting end on home NavLink

  • ❌ Trying to use useNavigate outside Router

  • ❌ Hard-refreshing after navigation


βœ… When to Use What?

Use Case

Recommended

Simple navigation

Link

Menu with active state

NavLink

Button / logic-based navigation

useNavigate()