React Router

React Router (Navigation & Routing)

React Router is a popular library that enables navigation and routing in React applications. It allows users to switch between different views (pages) without reloading the entire page, providing a seamless user experience.

Installing React Router

To use React Router, you need to install the package:

npm install react-router-dom

Basic Routing Setup

React Router defines navigation using the BrowserRouter, Routes, and Route components.

👉 Example: Setting Up Routes

import React from ‘react’;
import { BrowserRouter as Router, Routes, Route } from ‘react-router-dom’;

function Home() {
return <h1>Home Page</h1>;
}

function About() {
return <h1>About Page</h1>;
}

function App() {
return (
<Router>
<Routes>
<Route path=”/” element={<Home />} />
<Route path=”/about” element={<About />} />
</Routes>
</Router>
);
}

export default App;

📝 Explanation

✔️ BrowserRouter (Router) → Wraps the entire application to enable routing.
✔️ Routes → Groups multiple <Route> components.
✔️ Route → Defines individual routes with path and element.
✔️ path=”/” → Home page.
✔️ path=”/about” → About page.

Navigation with Link

Instead of using <a> tags, React Router provides the <Link> component for navigation.

👉 Example: Navigation Links

import React from “react”;
import { 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 Navbar() {
return (
<nav>
<Link to=”/”>Home</Link> | <Link to=”/about”>About</Link>
</nav>
);
}

function App() {
return (
<Router>
<Navbar />
<Routes>
<Route path=”/” element={<Home />} />
<Route path=”/about” element={<About />} />
</Routes>
</Router>
);
}

export default App;

📝 Explanation

✔️ <Link> → Used instead of <a> to prevent page reloads.
✔️ to=”/” → Navigates to the Home page.
✔️ to=”/about” → Navigates to the About page.

📌 Why Use Link Instead of ?

✅ Prevents full-page reloads.
✅ Improves performance by keeping the app state.

Using useNavigate for Programmatic Navigation

React Router provides the useNavigate hook to navigate programmatically.

👉 Example: Redirecting on Button Click

This example demonstrates how to navigate to another page when a button is clicked using useNavigate() from react-router-dom.

import React from “react”;
import { BrowserRouter as Router, Routes, Route, useNavigate } from “react-router-dom”;

function Home() {
const navigate = useNavigate();

return (
<div>
<h1>Home Page</h1>
<button onClick={() => navigate(‘/about’)}>Go to About</button>
</div>
);
}

function About() {
return <h1> About Page</h1>;
}

function App() {
return (
<Router>
<Routes>
<Route path=”/” element={<Home />} />
<Route path=”/about” element={<About />} />
</Routes>
</Router>
);
}

export default App;

📝 Explanation

✔️ useNavigate() → React Hook for programmatic navigation.
✔️ navigate(‘/about’) → Redirects to the About page when the button is clicked.

Dynamic Routing with URL Parameters

React Router allows passing parameters in the URL for dynamic content.

👉 Example: Route with a Dynamic Parameter

import React from “react”;

import { BrowserRouter as Router, Routes, Route, Link, useParams } from “react-router-dom”;

function Home() {
return <h1>Home Page</h1>;
}

function UserProfile() {
const { userId } = useParams();
return <h1>User Profile: {userId}</h1>;
}

function Navbar() {
return (
<nav>
<Link to=”/”>Home</Link> |
<Link to=”/user/101″>User 101</Link> |
<Link to=”/user/202″>User 202</Link>
</nav>
);
}

function App() {
return (
<Router>
<Navbar />
<Routes>
<Route path=”/” element={<Home />} />
<Route path=”/user/:userId” element={<UserProfile />} />
</Routes>
</Router>
);
}

export default App;

📝 Explanation

✔️ /user/:userId → The :userId is a dynamic parameter.
✔️ useParams() → Extracts the value from the URL.
✔️ <h1>User Profile: {userId}</h1> → Displays the user’s ID dynamically.

📌 Setting Up the Route:

<Route path=”/user/:userId” element={<UserProfile />} />

✔️ The :userId is a dynamic segment that changes based on the URL.
✔️ The UserProfile component will receive this userId using useParams().

📌 Navigating to Dynamic Routes:

<Link to=”/user/123″>View Profile</Link>

Nested Routes

React Router supports nested routing for better organization.

👉 Example: Parent and Child Routes

This example demonstrates nested routing using React Router’s <Outlet /> component.

import React from “react”;
import { BrowserRouter as Router, Routes, Route, Outlet, Link } from “react-router-dom”;

function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<nav>
<Link to=”settings”>Go to Settings</Link>
</nav>
<Outlet /> {/* This will render child routes */}
</div>
);
}

function Settings() {
return <h1>Settings</h1>;
}

function App() {
return (
<Router>
<Routes>
<Route path=”dashboard” element={<Dashboard />}>
<Route path=”settings” element={<Settings />} />
</Route>
</Routes>
</Router>
);
}

export default App;

📝 Explanation

✔️ Dashboard (Parent Route) → Renders a layout and uses <Outlet /> for child components.
✔️ Settings (Child Route) → Nested inside Dashboard.
✔️ <Route path=”dashboard”> → Defines the parent route.
✔️ <Outlet /> → Tells React Router where to render the child route.
✔️ <Route path=”settings”> → A sub-route inside dashboard.

Handling 404 Pages

To handle unknown routes, use a wildcard (*).

👉 Example: 404 Page

This example demonstrates how to handle 404 (Page Not Found) errors in a React application using React Router.

import React from “react”;
import { 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 NotFound() {
return <h1>404 – Page Not Found</h1>;
}

function App() {
return (
<Router>
<nav>
<Link to=”/”>Home</Link> | <Link to=”/about”>About</Link> | <Link to=”/random”>Invalid Link</Link>
</nav>

<Routes>
<Route path=”/” element={<Home />} />
<Route path=”/about” element={<About />} />

{/* 404 Page – Catch-all Route */}
<Route path=”*” element={<NotFound />} />
</Routes>
</Router>
);
}

export default App;

📝 Explanation

✔️ NotFound Component → Displays a custom 404 error message.
✔️ Wildcard Route (path=”*”) → Catches all unmatched routes.
✔️<Route path=”*”> → Ensures that if a user visits an undefined route, they see the NotFound component.

Conclusion

✅ React Router enables smooth navigation in React apps.
✅ Use <Routes> and <Route> for defining paths.
✅ <Link> prevents full-page reloads.
✅ useNavigate helps in programmatic navigation.
✅Dynamic and nested routes improve structure.
✅ Handle unknown routes with a 404 page.

Course Video in English

Chatbot