Lesson 45 of 60 – Navigation
75%

React Navigation

Navigation allows users to move between different pages and sections of a React application. React Router provides several tools for navigation, including Link, NavLink, and the useNavigate Hook.

Note: In a React Router application, navigation can happen without traditional full-page navigation. React Router changes the route and displays the appropriate component.

1. What is Navigation?

Navigation means moving from one route or page to another within an application.

For example:

/home
/about
/courses
/contact

Users can navigate between these routes using links, menus, buttons, or programmatic navigation.

2. Navigation in React Router

React Router provides tools that make navigation between application routes easier.

Common navigation tools include:

  • Link
  • NavLink
  • useNavigate

3. Navigation with Link

The Link component is one of the simplest ways to navigate between routes.

import { Link } from "react-router-dom";

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

Clicking the link navigates to the /about route.

4. The to Prop

The to prop specifies where the Link should navigate.

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

The destination in this example is /contact.

5. Creating a Navigation Menu

import { Link } from "react-router-dom";

function Navbar() {

    return (
        <nav>

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

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

            <Link to="/courses">
                Courses
            </Link>

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

        </nav>
    );
}

6. NavLink

NavLink is similar to Link, but it provides information about whether the current link matches the active route.

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

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

This is useful for navigation menus where the active page should look different.

7. Active Navigation Link

An active navigation link can be styled differently from other links.

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

The isActive value tells you whether the link currently matches the active route.

8. Styling NavLink

You can use a function with className to apply different classes.

<NavLink
    to="/courses"
    className={({ isActive }) =>
        isActive
            ? "nav-link active"
            : "nav-link"
    }
>
    Courses
</NavLink>

9. useNavigate Hook

The useNavigate Hook allows a component to navigate programmatically.

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

function Home() {

    const navigate = useNavigate();

    return (
        <button onClick={() => navigate("/about")}>
            Go to About
        </button>
    );
}

10. Programmatic Navigation

Programmatic navigation means changing the route using JavaScript rather than clicking a Link.

const navigate = useNavigate();

navigate("/dashboard");

This can be useful after actions such as submitting a form or completing a login process.

11. Navigation After Form Submission

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

function Login() {

    const navigate = useNavigate();

    function handleLogin() {

        // Login logic

        navigate("/dashboard");
    }

    return (
        <button onClick={handleLogin}>
            Login
        </button>
    );
}

After the login logic completes, the user can be navigated to the dashboard.

12. Navigation After Registration

Programmatic navigation can also be used after registration.

function Register() {

    const navigate = useNavigate();

    function handleRegister() {

        // Registration logic

        navigate("/login");
    }

    return (
        <button onClick={handleRegister}>
            Register
        </button>
    );
}

13. Navigate Back

The navigate function can also move backward in the browser history.

const navigate = useNavigate();

navigate(-1);

The value -1 moves back one history entry.

14. Navigate Forward

You can move forward in browser history by using a positive number.

const navigate = useNavigate();

navigate(1);

This moves forward one history entry when a forward entry exists.

15. Navigation with a Button

function Home() {

    const navigate = useNavigate();

    return (
        <button
            className="btn btn-primary"
            onClick={() => navigate("/about")}
        >
            About
        </button>
    );
}

This allows a button to perform navigation.

16. Link vs useNavigate

Link useNavigate
Used for visible navigation links Used for programmatic navigation
Usually clicked by the user Can be triggered by JavaScript logic
Simple navigation Useful after actions
<Link to="/about">
    About
</Link>

navigate("/about");

17. NavLink vs Link

Link NavLink
Basic navigation Navigation with active state information
No built-in active styling information Provides isActive
Simple links Navigation menus

18. Navigation with Route Parameters

Navigation can also be used with dynamic route parameters.

const studentId = 101;

<Link to={`/students/${studentId}`}>
    View Student
</Link>

The resulting URL is:

/students/101

19. Programmatic Navigation with Parameters

const navigate = useNavigate();

const studentId = 101;

navigate(`/students/${studentId}`);

This is useful when the destination depends on a value calculated or received by the application.

20. Navigation in a Dashboard

A dashboard can provide navigation to different sections.

function DashboardMenu() {

    return (
        <nav>

            <NavLink to="/dashboard">
                Home
            </NavLink>

            <NavLink to="/dashboard/profile">
                Profile
            </NavLink>

            <NavLink to="/dashboard/settings">
                Settings
            </NavLink>

        </nav>
    );
}

21. Navigation in a Sidebar

A sidebar can use NavLink to provide navigation and highlight the current section.

function Sidebar() {

    return (
        <aside>

            <NavLink to="/dashboard">
                Dashboard
            </NavLink>

            <NavLink to="/students">
                Students
            </NavLink>

            <NavLink to="/courses">
                Courses
            </NavLink>

            <NavLink to="/settings">
                Settings
            </NavLink>

        </aside>
    );
}

22. Active Link Styling with Bootstrap

If Bootstrap is used, classes can be conditionally applied to the active navigation item.

<NavLink
    to="/dashboard"
    className={({ isActive }) =>
        isActive
            ? "nav-link active bg-primary text-white"
            : "nav-link"
    }
>
    Dashboard
</NavLink>

23. Navigation with Query Strings

A navigation URL can also contain a query string.

<Link to="/products?category=mobile">
    Mobile Products
</Link>

The URL contains:

/products?category=mobile

Query strings can be useful for filters, searches, and other URL-based options.

24. Navigation from a Child Component

A child component can use useNavigate when it needs to navigate programmatically.

function StudentCard() {

    const navigate = useNavigate();

    function viewStudent() {
        navigate("/students/101");
    }

    return (
        <button onClick={viewStudent}>
            View Student
        </button>
    );
}

25. Navigation After Saving Data

After successfully saving data, an application can navigate the user to another page.

async function saveStudent() {

    // Save student data

    navigate("/students");
}

This can provide a simple workflow after successful operations.

26. Common Navigation Mistakes

  • Forgetting to import Link, NavLink, or useNavigate.
  • Using useNavigate outside router context.
  • Using incorrect route paths.
  • Forgetting the to prop on Link.
  • Using the wrong dynamic parameter.
  • Creating links to routes that do not exist.
  • Using programmatic navigation when a simple Link is sufficient.

27. Navigation Workflow

A typical navigation workflow is:

User Action
     ↓
Link / NavLink / Button
     ↓
Route Changes
     ↓
React Router Matches Route
     ↓
Component Displays

For programmatic navigation, JavaScript can trigger the route change.

28. Complete Navigation Example

import {
    BrowserRouter,
    Routes,
    Route,
    NavLink
} from "react-router-dom";

function Home() {
    return <h2>Home Page</h2>;
}

function About() {
    return <h2>About Page</h2>;
}

function Contact() {
    return <h2>Contact Page</h2>;
}

function App() {

    return (
        <BrowserRouter>

            <nav>

                <NavLink to="/">
                    Home
                </NavLink>

                {" | "}

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

                {" | "}

                <NavLink to="/contact">
                    Contact
                </NavLink>

            </nav>

            <Routes>

                <Route
                    path="/"
                    element={<Home />}
                />

                <Route
                    path="/about"
                    element={<About />}
                />

                <Route
                    path="/contact"
                    element={<Contact />}
                />

            </Routes>

        </BrowserRouter>
    );
}

export default App;

29. Complete useNavigate Example

import {
    BrowserRouter,
    Routes,
    Route,
    useNavigate
} from "react-router-dom";

function Home() {

    const navigate = useNavigate();

    return (
        <div>

            <h2>Home Page</h2>

            <button
                onClick={() => navigate("/about")}
                className="btn btn-primary"
            >
                Go to About
            </button>

        </div>
    );
}

function About() {
    return <h2>About Page</h2>;
}

function App() {

    return (
        <BrowserRouter>

            <Routes>

                <Route
                    path="/"
                    element={<Home />}
                />

                <Route
                    path="/about"
                    element={<About />}
                />

            </Routes>

        </BrowserRouter>
    );
}

export default App;

30. Navigation Best Practices

  • Use Link for simple internal navigation.
  • Use NavLink when active link styling is required.
  • Use useNavigate for programmatic navigation.
  • Keep navigation menus reusable.
  • Use meaningful route paths.
  • Make active navigation easy to identify.
  • Test navigation on every important route.
  • Use dynamic URLs carefully.
  • Do not create unnecessary programmatic navigation.
  • Keep navigation logic simple and predictable.
Link → Simple Navigation

NavLink → Active Navigation

useNavigate → Programmatic Navigation

📌 Key Points

  • Link is used for simple navigation between routes.
  • NavLink can identify the active route.
  • useNavigate provides programmatic navigation.
  • navigate(-1) moves back in browser history.
  • Dynamic values can be included in navigation URLs.
  • Navigation can be used in menus, sidebars, forms, and buttons.
  • All navigation should point to valid application routes.

🧠 Quick Quiz

Question: Which React Router Hook is used for programmatic navigation?