Routing in web applications refers to the mechanism by which different components or pages are rendered based on the URL in the browser's address bar. In Single Page Applications (SPAs) built with React, this navigation happens without a full page reload, providing a smoother user experience. React Router is the most popular and robust library for handling routing in React applications.
Why Use React Router?
* Declarative Routing: It allows you to define your routes as React components, making your routing logic readable and maintainable.
* Component-Based: It fits naturally into React's component-driven architecture, enabling route-specific components to be rendered.
* Dynamic & Nested Routes: Supports complex routing patterns, including routes with dynamic parameters (e.g., `/users/:id`) and nested route structures for layouts.
* History Management: Seamlessly integrates with the browser's history API, allowing users to use back/forward buttons.
* Programmatic Navigation: Provides hooks to navigate users to different routes based on actions (e.g., form submission, login).
Core Components and Hooks of `react-router-dom`:
1. `BrowserRouter`:
* Purpose: This is the foundational router component. It uses the HTML5 history API (pushState, replaceState, popstate events) to keep your UI in sync with the URL.
* Usage: You typically wrap your entire React application or the part of it that needs routing within `<BrowserRouter>`.
```jsx
import { BrowserRouter } from 'react-router-dom';
// ...
<BrowserRouter>
{/* Your app components that need routing */}
</BrowserRouter>
```
2. `Routes`:
* Purpose: A container component that groups multiple `<Route>` components. It iterates through its children `<Route>`s and renders the *first* one that matches the current URL.
* Usage: All your `<Route>` definitions should be nested inside a `<Routes>` component.
```jsx
import { Routes } from 'react-router-dom';
// ...
<Routes>
{/* Individual Route components */}
</Routes>
```
3. `Route`:
* Purpose: Defines a specific path and the React element to render when that path matches the current URL.
* Props:
* `path`: A string representing the URL path (e.g., `/`, `/about`, `/users/:id`).
* `element`: The React element (JSX) to render when the path matches.
* Dynamic Segments: Paths can include dynamic segments like `:id`. The value of `:id` can be accessed using the `useParams` hook.
```jsx
import { Route } from 'react-router-dom';
// ...
<Route path="/" element={<HomePage />} />
<Route path="/products/:productId" element={<ProductDetail />} />
```
4. `Link`:
* Purpose: Used to create navigation links within your application. It renders an accessible `<a>` tag in the DOM but prevents a full page reload, allowing React Router to handle the URL change internally.
* Props:
* `to`: The path to navigate to (e.g., `/about`).
```jsx
import { Link } from 'react-router-dom';
// ...
<Link to="/about">Go to About Page</Link>
```
5. `useNavigate` (Hook):
* Purpose: Provides a function that lets you navigate programmatically. This is useful for scenarios where navigation isn't triggered by a `Link` click (e.g., after a form submission, upon login/logout, or clicking a button that's not a link).
* Usage: Call `useNavigate()` to get a navigate function, then call `navigate('/path')` to change the route. `navigate(-1)` goes back in history.
```jsx
import { useNavigate } from 'react-router-dom';
// ...
function MyComponent() {
const navigate = useNavigate();
const handleSubmit = () => {
// ... (form submission logic)
navigate('/dashboard'); // Redirect to dashboard
};
return <button onClick={handleSubmit}>Submit and Go to Dashboard</button>;
}
```
6. `useParams` (Hook):
* Purpose: Allows you to access the dynamic parameters from the URL. If your route path is `/users/:id`, `useParams` will give you an object `{ id: 'some-value' }`.
* Usage: Destructure the parameters from the object returned by `useParams()`.
```jsx
import { useParams } from 'react-router-dom';
// ...
function UserProfile() {
const { id } = useParams();
return <h1>User Profile for ID: {id}</h1>;
}
```
Basic Example Workflow:
1. Installation: `npm install react-router-dom` or `yarn add react-router-dom`.
2. Root Component: Wrap your main `App` component with `BrowserRouter` (usually in `index.js`).
3. App Component: Define your navigation (`Link`s) and routing logic (`Routes` and `Route`s).
4. Page Components: Create individual React components for each route.
Example Code
First, install `react-router-dom`:
```bash
npm install react-router-dom
# or
yarn add react-router-dom
```
Then, set up your React application files:
`src/index.js`
```jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './index.css'; // Optional: for basic styling
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
```
`src/App.js`
```jsx
import React from 'react';
import { Routes, Route, Link, useNavigate } from 'react-router-dom';
import HomePage from './components/HomePage';
import AboutPage from './components/AboutPage';
import ContactPage from './components/ContactPage';
import UserProfile from './components/UserProfile';
import NotFoundPage from './components/NotFoundPage';
import Dashboard from './components/Dashboard';
function App() {
const navigate = useNavigate(); // Get navigate function for programmatic navigation
const handleGoToDashboard = () => {
navigate('/dashboard');
};
return (
<div className="App">
<nav style={{ padding: '10px', borderBottom: '1px solid #ccc' }}>
<ul style={{ listStyle: 'none', padding: 0, display: 'flex', gap: '20px' }}>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
<li>
<Link to="/users/123">User 123 Profile</Link>
</li>
<li>
<Link to="/users/456">User 456 Profile</Link>
</li>
<li>
<button onClick={handleGoToDashboard} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'blue', textDecoration: 'underline' }}>
Go to Dashboard (Programmatic)
</button>
</li>
</ul>
</nav>
<div style={{ padding: '20px' }}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/contact" element={<ContactPage />} />
<Route path="/users/:userId" element={<UserProfile />} /> {/* Dynamic route segment */}
<Route path="/dashboard" element={<Dashboard />} />
<Route path="*" element={<NotFoundPage />} /> {/* Catch-all route for unmatched paths */}
</Routes>
</div>
</div>
);
}
export default App;
```
`src/components/HomePage.js`
```jsx
import React from 'react';
function HomePage() {
return (
<div>
<h1>Welcome to the Home Page!</h1>
<p>This is the landing page of our application.</p>
</div>
);
}
export default HomePage;
```
`src/components/AboutPage.js`
```jsx
import React from 'react';
function AboutPage() {
return (
<div>
<h1>About Us</h1>
<p>Learn more about our company and mission here.</p>
</div>
);
}
export default AboutPage;
```
`src/components/ContactPage.js`
```jsx
import React from 'react';
function ContactPage() {
return (
<div>
<h1>Contact Us</h1>
<p>Feel free to reach out to us!</p>
</div>
);
}
export default ContactPage;
```
`src/components/UserProfile.js`
```jsx
import React from 'react';
import { useParams, useNavigate } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams(); // Access the dynamic parameter 'userId'
const navigate = useNavigate();
const handleGoBack = () => {
navigate(-1); // Go back one step in browser history
};
return (
<div>
<h1>User Profile</h1>
<p>Displaying profile for user with ID: <strong>{userId}</strong></p>
<button onClick={handleGoBack}>Go Back</button>
</div>
);
}
export default UserProfile;
```
`src/components/Dashboard.js`
```jsx
import React from 'react';
import { useNavigate } from 'react-router-dom';
function Dashboard() {
const navigate = useNavigate();
const handleLogout = () => {
// Simulate logout logic
alert('Logging out...');
navigate('/'); // Redirect to home page after logout
};
return (
<div>
<h1>Dashboard</h1>
<p>This is your personalized dashboard area.</p>
<button onClick={handleLogout}>Logout</button>
</div>
);
}
export default Dashboard;
```
`src/components/NotFoundPage.js`
```jsx
import React from 'react';
import { Link } from 'react-router-dom';
function NotFoundPage() {
return (
<div>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
<p>
You can go back to the <Link to="/">home page</Link>.
</p>
</div>
);
}
export default NotFoundPage;
```








Routing (React Router)