Module 3: React Router

Learn React Router for navigation, routing, and building single-page applications. Master client-side routing in React.

Back to Course|4 hours|Intermediate

React Router

Learn React Router for navigation, routing, and building single-page applications. Master client-side routing in React.

Progress: 0/4 topics completed0%

Select Topics Overview

React Router Basics

Learn the fundamentals of React Router for navigation in React applications

Content by: Chirag Gupta

MERN Stack Developer

Connect

What is React Router?

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.

Key Features

  • Declarative routing for React applications
  • Nested routing support
  • Dynamic routing with parameters
  • Programmatic navigation
  • Browser history management

Basic Setup

Code Example
// 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>
    );
}
Swipe to see more code

Practice Exercise: Basic Router Setup

Code Example
// 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
Swipe to see more code

🎯 Practice Exercise

Test your understanding of this topic:

Additional Resources

📚 Recommended Reading

  • React Router Documentation
  • React Router v6 Guide
  • Client-Side Routing Best Practices

🌐 Online Resources

  • React Router Tutorial
  • Nested Routes Examples
  • Programmatic Navigation Guide

Ready for the Next Module?

Continue your learning journey and master the next set of concepts.

Continue to Module 4