Routing with React Router
Navigating between different pages without reloading the browser using React Router.
Learning Goals
The Core Concept
React is primarily used to build Single Page Applications (SPAs). This means the browser only ever loads one HTML file. To create the illusion of navigating between multiple pages (like Home, About, and Contact), we use routing libraries like React Router. It watches the URL in the browser's address bar and swaps out which React components are currently visible on the screen, instantly, without a slow page refresh.
Visual guide
React concept flow
A simple original diagram to connect the lesson idea with real project flow.
Code & Implementation
// Requires: npm install react-router-dom
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function Home() { return <h2>Home Page</h2>; }
function About() { return <h2>About Us</h2>; }
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}Expected Output
Home | About Home Page
Blog Application
Hands-on practice task
The Challenge
A simple multi-page blog. It has a home page showing a list of post titles, and clicking a title navigates to a detailed view of that post.
Helpful Hints
- •Set up React Router with two routes: `/` (Home) and `/post/:id` (Post Detail).
- •Create a hardcoded array of blog posts in a separate file to act as your database.
- •In the Post Detail component, use the `useParams` hook to get the ID from the URL and display the correct post.
Quick Knowledge Check
How do I redirect a user programmatically (e.g., after login)?
Continue Learning
Next steps after this lesson
A simple multi-page blog. It has a home page showing a list of post titles, and clicking a title navigates to a detailed view of that post.
Supercharge your career workflows!
Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.