React Router
Subject: React
Routing in React Router v6 (Core Concepts)
React Router helps manage navigation between different pages in a Single Page Application (SPA). It updates the UI without reloading the full page.
β 1. Installation
π§± 2. Basic Setup
π§Ύ Explanation
Term | Description |
---|---|
BrowserRouter | Provides routing context using the browser history API |
Routes | Wrapper for all Route definitions |
Route | Maps a path (URL) to a component (element) |
path="*" | Wildcard route for handling 404s (NotFound page) |
π 3. Creating Pages
π 4. Navigation Between Pages
Component | Purpose |
---|---|
Link | Navigates between routes (no page reload) |
π§ Summary (Routing Concepts)
Feature | React Router v6 Syntax |
---|---|
Routes container | <Routes> |
Route matching | Exact by default |
Wildcard route | path="*" |
Navigation | <Link to="..."> |
Nested Routes | Fully supported |
π Part 2: React Router v6 Hooks (useNavigate, useParams, etc.)
Hooks make navigation and route data access easier in functional components.
π 1. useNavigate()
Navigate programmatically (e.g., after a button click):
πΊοΈ 2. useParams()
Access dynamic route parameters:
Used like:
π 3. useLocation()
Access info about the current route (URL, search, hash, etc):
π€ 4. useSearchParams()
Handle query strings (like ?sort=asc&page=2
):
URL Example: /products?sort=asc
π Wrap-Up
π Routing handles:
- URL to component mapping
- Navigation links
- Wildcard route handling (404)
- Layouts & nested routing
π§ͺ React Router Hooks:
Hook | Purpose |
---|---|
useNavigate() | Redirect programmatically |
useParams() | Access dynamic route values |
useLocation() | Get info about the current URL |
useSearchParams() | Work with query strings |
React Router v6 makes routing in React apps simple, powerful, and flexible for both beginners and advanced developers.
Advertisement Slot 1
Advertisement Slot 2