Router
React Router is a standard library for routing in React. It enables navigation among views of various components in a React application, allows the browser URL to reflect the app state, and keeps the UI in sync with the URL.
Key Concepts
Routes: Define the mappings between URL paths and React components.
Router: The top-level component that provides routing functionality.
Link: A component to navigate around the application without reloading the page.
useNavigate, useParams, useLocation: React hooks for navigation, accessing URL parameters, and location state.
Installation
npm install react-router-dom
For projects using React Native, use react-router-native.
Basic Example
import React from 'react';
import {
BrowserRouter as Router,
Routes,
Route,
Link
} from 'react-router-dom';
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
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;
Common Features
Nested Routes: Structure your routes like your UI structure.
Route Parameters: Capture values from the URL (/user/:id).
Redirects: Navigate programmatically or with <Navigate />.
Lazy Loading: Load components only when needed using React.lazy.