Learn React Router for navigation, routing, and building single-page applications. Master client-side routing in React.
Learn React Router for navigation, routing, and building single-page applications. Master client-side routing in React.
Learn the fundamentals of React Router for navigation in React applications
Content by: Chirag Gupta
MERN Stack Developer
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.
// Install React Router
npm install react-router-dom
// Basic Router Setup
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}
// Navigation Component
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}
// Complete Example with Components
function Home() {
return (
<div>
<h1>Welcome to Our App</h1>
<p>This is the home page of our React application.</p>
</div>
);
}
function About() {
return (
<div>
<h1>About Us</h1>
<p>Learn more about our company and mission.</p>
</div>
);
}
function Contact() {
return (
<div>
<h1>Contact Us</h1>
<p>Get in touch with our team.</p>
</div>
);
}
// Enhanced Navigation with Active States
function EnhancedNavigation() {
const location = useLocation();
return (
<nav className="navigation">
<Link
to="/"
className={location.pathname === '/' ? 'active' : ''}
>
Home
</Link>
<Link
to="/about"
className={location.pathname === '/about' ? 'active' : ''}
>
About
</Link>
<Link
to="/contact"
className={location.pathname === '/contact' ? 'active' : ''}
>
Contact
</Link>
</nav>
);
}
// Exercise: Build a Multi-Page Blog Application
// Create a blog application with React Router
// src/App.js
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Navigation from './components/Navigation';
import Home from './pages/Home';
import BlogList from './pages/BlogList';
import BlogPost from './pages/BlogPost';
import About from './pages/About';
import Contact from './pages/Contact';
function App() {
return (
<BrowserRouter>
<div className="app">
<Navigation />
<main className="main-content">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/blog" element={<BlogList />} />
<Route path="/blog/:id" element={<BlogPost />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</main>
</div>
</BrowserRouter>
);
}
// src/components/Navigation.js
import { Link, useLocation } from 'react-router-dom';
function Navigation() {
const location = useLocation();
return (
<nav className="navbar">
<div className="nav-brand">
<Link to="/">MyBlog</Link>
</div>
<ul className="nav-links">
<li>
<Link
to="/"
className={location.pathname === '/' ? 'active' : ''}
>
Home
</Link>
</li>
<li>
<Link
to="/blog"
className={location.pathname.startsWith('/blog') ? 'active' : ''}
>
Blog
</Link>
</li>
<li>
<Link
to="/about"
className={location.pathname === '/about' ? 'active' : ''}
>
About
</Link>
</li>
<li>
<Link
to="/contact"
className={location.pathname === '/contact' ? 'active' : ''}
>
Contact
</Link>
</li>
</ul>
</nav>
);
}
// src/pages/Home.js
function Home() {
return (
<div className="home">
<h1>Welcome to MyBlog</h1>
<p>Discover amazing stories and insights.</p>
<Link to="/blog" className="cta-button">
Read Our Blog
</Link>
</div>
);
}
// src/pages/BlogList.js
function BlogList() {
const posts = [
{ id: 1, title: 'Getting Started with React', excerpt: 'Learn the basics...' },
{ id: 2, title: 'Advanced React Patterns', excerpt: 'Master complex patterns...' },
{ id: 3, title: 'React Performance Tips', excerpt: 'Optimize your apps...' }
];
return (
<div className="blog-list">
<h1>Blog Posts</h1>
<div className="posts-grid">
{posts.map(post => (
<article key={post.id} className="post-card">
<h2>{post.title}</h2>
<p>{post.excerpt}</p>
<Link to={`/blog/${post.id}`} className="read-more">
Read More
</Link>
</article>
))}
</div>
</div>
);
}
// src/pages/BlogPost.js
import { useParams, useNavigate } from 'react-router-dom';
function BlogPost() {
const { id } = useParams();
const navigate = useNavigate();
// Simulate fetching post data
const post = {
id: id,
title: `Blog Post ${id}`,
content: 'This is the full content of the blog post...',
author: 'John Doe',
date: '2025-01-15'
};
return (
<article className="blog-post">
<button onClick={() => navigate('/blog')} className="back-button">
← Back to Blog
</button>
<h1>{post.title}</h1>
<div className="post-meta">
<span>By {post.author}</span>
<span>{post.date}</span>
</div>
<div className="post-content">
{post.content}
</div>
</article>
);
}
// Challenge: Add a search functionality to the blog
// Challenge: Add pagination to the blog list
// Challenge: Add categories and filtering
Test your understanding of this topic:
Learn to handle dynamic routes and URL parameters in React Router
Content by: Harmi Savani
MERN Stack Developer
URL parameters allow you to create dynamic routes that can accept different values. They are defined in the route path using a colon followed by the parameter name.
// Route with parameter
<Route path="/user/:id" element={<UserProfile />} />
// Component using useParams
import { useParams } from 'react-router-dom';
function UserProfile() {
const { id } = useParams();
return (
<div>
<h1>User Profile</h1>
<p>User ID: {id}</p>
</div>
);
}
// Multiple parameters
<Route path="/user/:id/posts/:postId" element={<UserPost />} />
function UserPost() {
const { id, postId } = useParams();
return (
<div>
<h1>User Post</h1>
<p>User ID: {id}</p>
<p>Post ID: {postId}</p>
</div>
);
}
// Using query parameters
import { useSearchParams } from 'react-router-dom';
function ProductList() {
const [searchParams, setSearchParams] = useSearchParams();
const category = searchParams.get('category');
const sort = searchParams.get('sort');
return (
<div>
<h1>Products</h1>
<p>Category: {category}</p>
<p>Sort: {sort}</p>
<button onClick={() => setSearchParams({ category: 'electronics' })}>
Electronics
</button>
<button onClick={() => setSearchParams({ sort: 'price' })}>
Sort by Price
</button>
</div>
);
}
Test your understanding of this topic:
Master nested routing to create complex navigation structures
Content by: Abhay Khanpara
MERN Stack Developer
Nested routes allow you to create a hierarchy of routes where child routes are rendered within parent routes. This is useful for creating layouts and complex navigation structures.
// Parent route with nested children
<Route path="/dashboard" element={<Dashboard />}>
<Route index element={<DashboardHome />} />
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
// Dashboard component with Outlet
import { Outlet } from 'react-router-dom';
function Dashboard() {
return (
<div>
<nav>
<Link to="/dashboard">Home</Link>
<Link to="/dashboard/profile">Profile</Link>
<Link to="/dashboard/settings">Settings</Link>
</nav>
<main>
<Outlet />
</main>
</div>
);
}
// Child components
function DashboardHome() {
return <h1>Dashboard Home</h1>;
}
function Profile() {
return <h1>User Profile</h1>;
}
function Settings() {
return <h1>Settings</h1>;
}
// Complex nested routing
<Route path="/admin" element={<AdminLayout />}>
<Route index element={<AdminDashboard />} />
<Route path="users" element={<UserManagement />}>
<Route index element={<UserList />} />
<Route path=":id" element={<UserDetail />} />
<Route path="new" element={<CreateUser />} />
</Route>
<Route path="products" element={<ProductManagement />}>
<Route index element={<ProductList />} />
<Route path=":id" element={<ProductDetail />} />
<Route path="new" element={<CreateProduct />} />
</Route>
</Route>
// Admin Layout Component
function AdminLayout() {
return (
<div className="admin-layout">
<header>
<h1>Admin Panel</h1>
<nav>
<Link to="/admin">Dashboard</Link>
<Link to="/admin/users">Users</Link>
<Link to="/admin/products">Products</Link>
</nav>
</header>
<main>
<Outlet />
</main>
</div>
);
}
Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 4