React Router Objectives

Understanding React Router

React Router is a powerful library that enables navigation and routing in React applications. It allows developers to manage application views efficiently, creating a smooth user experience similar to traditional websites.

Key Objectives

After completing this material, you should be able to:

Creating Routes

To define routes in your React application, use the react-router-dom package:


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

function App() {{
    return (
        <Router>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
            </Routes>
        </Router>
    );
}}

Using the Outlet Component

The Outlet component is used in parent routes to render nested child components dynamically.


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

function Layout() {{
    return (
        <div>
            <h1>My App</h1>
            <Outlet />
        </div>
    );
}}

Generating Navigation Links

To create navigable links, use the Link and NavLink components.


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

function Navigation() {{
    return (
        <nav>
            <NavLink to="/">Home</NavLink>
            <NavLink to="/about">About</NavLink>
        </nav>
    );
}}

Accessing Path Variables with useParams

The useParams hook allows access to dynamic segments in the URL.


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

function UserProfile() {{
    let {{ userId }} = useParams();
    return <h2>User ID: {{ userId }}</h2>;
}}

Redirecting Users with Navigate and useNavigate

The Navigate component and useNavigate hook enable programmatic navigation.


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

function RedirectComponent() {{
    return <Navigate to="/home" />;
}}

function ButtonNavigation() {{
    let navigate = useNavigate();
    return <button onClick={() => navigate("/dashboard")}>Go to Dashboard</button>;
}}

Further Exploration

To deepen your understanding, explore these topics:

Conclusion

React Router is essential for managing navigation in React applications. By mastering its features, developers can create dynamic, user-friendly, and scalable applications.