React Router Fundamentals

0/2 in this phase0/36 across the roadmap

📖 Concept

React is a Single Page Application (SPA) library, meaning it only has one HTML file. Routing is the process of deciding which components to show based on the current URL in the browser.

React Router (v6+) is the industry standard for routing in Vite/SPA apps.

Core Components:

  • BrowserRouter: The parent component that stores the current location and navigates using the browser's history API.
  • Routes & Route: Define the mapping between a path (e.g., /about) and a component (e.g., <About />).
  • Link: Use this instead of <a> tags to navigate without a full page reload.
  • Outlet: A placeholder for "nested routes". It's where the child route's component will be rendered.

💻 Code Example

codeTap to expand ⛶
1import { BrowserRouter, Routes, Route, Link, Outlet } from 'react-router-dom';
2
3// 1. Layout Component with <Outlet />
4function Layout() {
5 return (
6 <div>
7 <nav className="p-4 bg-gray-800 text-white flex space-x-4">
8 <Link to="/" className="hover:text-blue-400">Home</Link>
9 <Link to="/products" className="hover:text-blue-400">Products</Link>
10 <Link to="/about" className="hover:text-blue-400">About</Link>
11 </nav>
12 <main className="p-10">
13 <Outlet /> {/* Child routes render here */}
14 </main>
15 </div>
16 );
17}
18
19function App() {
20 return (
21 <BrowserRouter>
22 <Routes>
23 <Route path="/" element={<Layout />}>
24 <Route index element={<h1>Home Page</h1>} />
25 <Route path="about" element={<h1>About Us</h1>} />
26 <Route path="products" element={<ProductList />} />
27 <Route path="*" element={<h1>404: Not Found</h1>} />
28 </Route>
29 </Routes>
30 </BrowserRouter>
31 );
32}

🏋️ Practice Exercise

  1. Set up a basic React Router project with at least 3 pages.
  2. Implement a 'Navbar' that highlights the 'Active' link using NavLink.
  3. Create a nested route structure (e.g., /dashboard/settings and /dashboard/profile).
  4. Research why using regular <a> tags in a React app causes the entire app to re-bootstrap.

⚠️ Common Mistakes

  • Using <a> tags instead of <Link> (causing full page reloads and losing state).

  • Forgetting the <Outlet /> in a parent route, which prevents child routes from appearing.

  • Not handling 404 routes using the path="*" wildcard.

  • Nesting routes too deeply, making the URL structure confusing.

💼 Interview Questions

🎤 Mock Interview

Practice a live interview for React Router Fundamentals