REACT Router Basics

React Router is a powerful library that allows you to handle routing in a React application, enabling navigation between different components or views without reloading the entire page. It helps build single-page applications (SPAs) with a seamless user experience.

1. What is React Router?

React Router:

  • Manages navigation and rendering of components based on the URL.
  • Keeps the UI in sync with the browser’s URL.
  • Provides tools for dynamic routing, nested routes, and route parameters.

2. Installing React Router

To use React Router, install it via npm:

npm install react-router-dom

Try It Now

3. Basic Structure of React Router

React Router provides a set of components to define and control routes:

  1. <BrowserRouter>: Wraps the application and enables client-side routing.
  2. <Routes>: Acts as a container for all defined routes.
  3. <Route>: Defines a specific route and its corresponding component.
  4. <Link>: Creates navigation links without refreshing the page.

4. Setting Up Routes

Example: Basic Routing

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

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

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

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

function App() {
    return (
        <BrowserRouter>
            <nav>
                <Link to="/">Home</Link> | <Link to="/about">About</Link> | <Link to="/contact">Contact</Link>
            </nav>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
                <Route path="/contact" element={<Contact />} />
            </Routes>
        </BrowserRouter>
    );
}

export default App;

Try It Now

5. Key Components of React Router

  1. <BrowserRouter>:
    • Manages the history stack for client-side navigation.
    • Typically wraps the entire app.
  2. <Routes>:
    • Contains all route definitions.
    • Replaces the older <Switch> component in React Router v6+.
  3. <Route>:
    • Defines a single route.
    • Uses path for the URL and element for the component to render.
  4. <Link>:
    • Replaces traditional anchor tags (<a>).
    • Ensures navigation is handled by React Router without full-page reloads.

6. Nested Routes

React Router allows defining nested routes for hierarchical navigation.

Example: Nested Routes

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

function Dashboard() {
    return <h1>Dashboard</h1>;
}

function Profile() {
    return <h1>Profile</h1>;
}

function Settings() {
    return <h1>Settings</h1>;
}

function App() {
    return (
        <BrowserRouter>
            <nav>
                <Link to="/dashboard">Dashboard</Link>
                <Link to="/dashboard/profile">Profile</Link>
                <Link to="/dashboard/settings">Settings</Link>
            </nav>
            <Routes>
                <Route path="/dashboard" element={<Dashboard />}>
                    <Route path="profile" element={<Profile />} />
                    <Route path="settings" element={<Settings />} />
                </Route>
            </Routes>
        </BrowserRouter>
    );
}

export default App;

Try It Now

7. Dynamic Routes

Dynamic routes allow passing parameters in the URL.

Example: Dynamic Routing

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

function User() {
    const { id } = useParams();
    return <h1>User ID: {id}</h1>;
}

function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/user/:id" element={<User />} />
            </Routes>
        </BrowserRouter>
    );
}

export default App;

Try It Now

8. Redirects and Navigation

React Router provides ways to navigate programmatically and handle redirects.

Example: Programmatic Navigation

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

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

    const goToAbout = () => {
        navigate("/about");
    };

    return (
        <div>
            <h1>Home Page</h1>
            <button onClick={goToAbout}>Go to About</button>
        </div>
    );
}

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

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

export default App;

Try It Now

9. Handling 404 (Not Found) Pages

You can define a fallback route for unmatched paths.

Example: 404 Page

function NotFound() {
    return <h1>404 - Page Not Found</h1>;
}

<Routes>
    <Route path="/" element={<Home />} />
    <Route path="*" element={<NotFound />} />
</Routes>;

Try It Now

10. Best Practices

  1. Use semantic URLs that reflect the content of the page.
  2. Group related routes together for modular code organization.
  3. Use lazy loading for large applications to optimize performance.
  4. Handle edge cases like undefined routes or invalid parameters gracefully.

React Router simplifies navigation and routing in React applications.