React Router DOM is a popular library in React that is used to handle navigation and routing in a React application.
It enables your React app to have multiple pages (views) and allows users to navigate between those pages without reloading the browser.
Key Features of React Router DOM:
Feature | Description |
---|---|
Single Page Application (SPA) | Allows multiple βpagesβ in a React app without full-page reloads. |
Dynamic Routing | Routes are defined using React components instead of static routes. |
Nested Routes | Support for child routes inside parent routes. |
URL Parameters | Pass data through URL (e.g., /product/:id ). |
Navigation Programmatically | Navigate using useNavigate() hook. |
Redirects & Protected Routes | Handle redirects and authentication-based navigation. |
Installation:
bashCopyEditnpm install react-router-dom
Basic Example Using React Router DOM:
1. Setting Up Routes:
javascriptCopyEditimport { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
function Home() {
return <h1>Home Page</h1>;
}
function About() {
return <h1>About Page</h1>;
}
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;
How It Works:
<Router>
: Wraps the entire application and enables routing.<Routes>
: Groups all the route definitions.<Route>
: Defines a route with apath
and theelement
(component) to render.<Link>
: Used for navigation without page reload.
Hooks in React Router DOM:
Hook | Purpose |
---|---|
useNavigate() | Programmatically navigate to different routes. |
useParams() | Access route parameters (e.g., /product/:id ). |
useLocation() | Get information about the current URL. |
Example: Navigate Programmatically:
javascriptCopyEditimport { useNavigate } from 'react-router-dom';
function Home() {
const navigate = useNavigate();
const goToAbout = () => {
navigate('/about');
};
return <button onClick={goToAbout}>Go to About</button>;
}
Benefits of React Router DOM:
β
Client-side navigation without reloading the entire page.
β
Improved user experience with smooth transitions between views.
β
Dynamic and nested routing support.
β
Simplifies routing management in large applications.
β
React-friendly (component-based) approach to navigation.
Final Summary:
React Router DOM is essential for building multi-page React applications.
It provides tools for navigation, URL parameters, redirects, and more,
allowing developers to create SPA applications with a smooth user experience. π