Topic 36 of 54
and BrowserRouter
Overview
React does not come with routing built-in. The industry standard library is `react-router-dom`. To use it, you must wrap your entire application in a `<BrowserRouter>` (which provides the routing context) and define your `<Routes>` (the map that tells React which component belongs to which URL).
Syntax
Run this in your terminal to install the library.
Installation
bash
npm install react-router-domWhen the URL changes to `/about`, React Router finds the matching `<Route>` and renders the `<About />` component inside the `<Routes>` block.
v6 syntax
bash
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
import NotFound from './NotFound';
function App() {
return (
// 1. BrowserRouter connects your app to the browser's URL history
<BrowserRouter>
{/* 2. Routes acts like a switch statement for your URLs */}
<Routes>
{/* 3. Route maps a specific URL path to a Component */}
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
{/* The asterisk (*) catches any URL that doesn't match above */}
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}Common Pitfalls
- Forgetting to wrap your app in `<BrowserRouter>`. If you try to use any routing hooks or Links without it, your app will crash with a Context error.
Interview Tips
- If you're looking at older codebases (React Router v5), you will see `<Switch>` and `component={Home}`. In modern v6+, it is `<Routes>` and `element={<Home />}`.
Real-World Example
Nested Routes are used to maintain a persistent Layout (like a Navbar) while the inner content changes.
example
bash
function App() {
return (
<BrowserRouter>
<Routes>
{/* The Layout component contains the Navbar and an <Outlet /> */}
<Route path="/" element={<Layout />}>
{/* These are nested inside the Layout */}
<Route index element={<Home />} />
<Route path="contact" element={<Contact />} />
</Route>
</Routes>
</BrowserRouter>
);
}