3rd Practical Class:
Routing in React
🎯 Learning Objectives (5 minutes)
By the end of this session, you will be able to:
- Understand client-side routing concepts in React applications
- Implement navigation with React Router v7
- Create dynamic routes with URL parameters
- Build nested routes and layouts
🤔 The Problem: Why Do We Need Client-Side Routing?
What happens without routing?
Problems with this approach:
- ❌ No URL changes: Users can't bookmark specific pages
- ❌ No browser history: Back/forward buttons don't work
- ❌ No deep linking: Can't share direct links to specific pages
- ❌ Poor SEO: Search engines can't index individual pages
- ❌ Manual state management: Complex state handling for navigation
- ❌ Performance: The whole javascript bundle is loaded for every page
🏗️ Building Blocks: React Router v7
Step 1: Basic Router Setup
React Router provides client-side routing for React applications:
Key Components:
- : Creates router configuration
- : Provides router context
- : Renders nested route components
- : Navigation component (prevents page reload)
Step 2: Exercise - Add a New Route
Your Turn! Add a new "Products" page to the router above.
⚡ Dynamic Routes and URL Parameters
Step 3: URL Parameters
React Router allows you to create dynamic routes with parameters:
Key Concepts:
- - Dynamic route parameter
- - Hook to access URL parameters
- Nested routes - and
🔒 Nested Routes and Layouts
Step 4: Layout Components
React Router supports nested routes for creating layouts:
Key Concepts:
- - Renders nested route components
- Nested components - Creates route hierarchy
- Layout components - Shared UI across multiple routes
🎯 Final Exercise: Build a Complete App
Your Challenge: Create a simple blog app with the following requirements:
-
Routes:
- Home page ()
- Blog posts list ()
- Individual post page ()
- About page ()
-
Features:
- Navigation between pages
- Dynamic routing for blog posts
- Mock data for posts
📚 Additional Resources
Next Steps: Explore advanced routing features like route guards, lazy loading, and integration with state management libraries.