React Routing

Overview

Routing is how you navigate between different views/pages in a React Single Page Application (SPA).

React doesn’t have built-in routing — we commonly use React Router for that.

1. Installing React Router

npm install react-router-dom

2. Core Components

ComponentPurpose
<BrowserRouter>Wraps the app to enable routing using browser history
<Routes>Contains individual route definitions
<Route path="" element={}>Defines a route for a specific URL
<Link to="">Navigates without reload
useNavigate()Programmatic navigation
useParams()Extracts route parameters
useLocation()Gives access to current location object

3. Basic Routing Example

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

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

4. Nested Routing

Allows defining routes inside other routes (e.g., /dashboard/profile).

<Route path="/dashboard" element={<Dashboard />}>
  <Route path="profile" element={<Profile />} />
</Route>
import { Outlet } from 'react-router-dom';

function Dashboard() {
  return (
    <>
      <h2>Dashboard</h2>
      <Outlet />
    </>
  );
}

5. Dynamic Routing

Used for URLs with dynamic segments (e.g., /user/:id)

<Route path="/user/:id" element={<UserDetail />} />
import { useParams } from 'react-router-dom';

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

6. Programmatic Navigation

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

function LoginButton() {
  const navigate = useNavigate();
  return (
    <button onClick={() => navigate('/dashboard')}>
      Go to Dashboard
    </button>
  );
}

Key Points

Always use <Link to=""> for internal navigation

Extract dynamic segments like :id using useParams()

Use useNavigate() for programmatic navigation

Use <Outlet /> in parent component to render nested routes

Always wrap your app with <BrowserRouter>

Bình luận

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *