React FAQ: Top 75 Questions
10. Explain React Router and its purpose.
React Router is a standard library for routing in React. It enables declarative routing for single-page applications (SPAs) built with React. In an SPA, the browser never actually navigates to a new HTML page; instead, React Router dynamically renders different components based on the URL in the browser's address bar. This provides a seamless user experience similar to traditional multi-page websites but with the performance benefits of an SPA.
Purpose of React Router:
- Declarative Navigation: Allows you to define routes as React components, integrating routing logic directly into your UI structure.
- Single Page Application (SPA) Navigation: Provides a way to navigate between different "views" or "pages" within a single HTML document without full page reloads. This makes the application feel faster and more fluid.
- URL Synchronization: Keeps the UI in sync with the URL. When the URL changes, React Router renders the appropriate components. Conversely, when the user interacts with navigation elements, React Router updates the URL.
- Nested Routing: Supports complex routing hierarchies where different parts of the UI can have their own nested routes.
- Programmatic Navigation: Offers methods to navigate programmatically (e.g., after a form submission or a successful API call) using the `Maps` hook or `history` object.
- Route Parameters: Allows for dynamic parts in URLs (e.g., `/users/:id`), enabling components to fetch data based on the URL parameter.
Key components of React Router (v6 and later):
- `BrowserRouter` / `HashRouter`: These are routers that enable client-side routing. `BrowserRouter` uses the HTML5 history API (clean URLs), while `HashRouter` uses the URL hash (e.g., `/#/about`). `BrowserRouter` is generally preferred.
- `Routes` / `Route`: `Routes` is a container for `Route` components. `Route` maps a URL path to a React component.
- `Link` / `NavLink`: Used for navigation. `Link` is a basic anchor tag replacement. `NavLink` is a special version of `Link` that can add styling attributes to the rendered element when it matches the current URL.
- `useParams`: A hook to access URL parameters (e.g., `id` in `/users/:id`).
- `useNavigate`: A hook to programmatically navigate.
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter as Router, Routes, Route, Link, NavLink, useParams, useNavigate } from 'react-router-dom';
// Home Component
function Home() {
return (
<div>
<h2>Home Page</h2>
<p>Welcome to our application!</p>
</div>
);
}
// About Component
function About() {
return (
<div>
<h2>About Us</h2>
<p>Learn more about our company.</p>
</div>
);
}
// User Profile Component (demonstrates useParams)
function UserProfile() {
const { id } = useParams(); // Get 'id' from URL params
const navigate = useNavigate(); // Get navigate function
const goToHome = () => {
navigate('/'); // Programmatic navigation
};
return (
<div>
<h2>User Profile for ID: {id}</h2>
<p>This is the profile page for user {id}.</p>
<button onClick={goToHome}>Go to Home (Programmatic)</button>
</div>
);
}
// Not Found Component
function NotFound() {
return (
<div>
<h2>404 - Page Not Found</h2>
<p>Sorry, the page you are looking for does not exist.</p>
</div>
);
}
function App() {
return (
<Router> {/* Wraps the entire application for routing */}
<nav>
<ul>
<li>
<NavLink to="/">Home</NavLink> {/* NavLink for active styling */}
</li>
<li>
<Link to="/about">About</Link> {/* Basic Link */}
</li>
<li>
<Link to="/users/123">User 123 Profile</Link>
</li>
<li>
<Link to="/users/abc">User ABC Profile</Link>
</li>
</ul>
</nav>
<Routes> {/* Defines the routing rules */}
<Route path="/" element={<Home />} /> {/* Exact path match for Home */}
<Route path="/about" element={<About />} />
<Route path="/users/:id" element={<UserProfile />} /> {/* Route with a parameter */}
<Route path="*" element={<NotFound />} /> {/* Catch-all for 404 */}
</Routes>
</Router>
);
}
const root = ReactDOM.createRoot(document.getElementById('root-router'));
root.render(<App />);
Explanation of the Code:
- **`Router` (e.g., `BrowserRouter`):** This wraps the entire application or the part of your application that needs routing.
- **`Link` and `NavLink`:** Used for client-side navigation. `NavLink` is preferred when you want to apply active styles to the link corresponding to the current URL.
-
**`Routes` and `Route`:**
- `Routes` acts as a container for all `Route` components. It ensures that only one `Route` matches the current URL.
- `Route` defines a specific path (`path`) and the component (`element`) to render when that path matches the URL.
- `path="/users/:id"` shows how to define a route with a dynamic parameter (`:id`).
- `path="*"` acts as a "catch-all" route for any unmatched URLs, useful for displaying a 404 page.
- **`useParams` Hook:** In `UserProfile` component, `useParams()` is used to extract the dynamic `id` from the URL, allowing the component to render content specific to that ID.
- **`useNavigate` Hook:** In `UserProfile`, `useNavigate()` provides a function (`Maps`) to change the URL programmatically, for example, redirecting the user to the home page after an action.
React Router is essential for building intuitive and performant SPAs, providing a robust way to manage navigation and URL synchronization within your React application.