What is React Router?
- React course
- Intermediate
- Lesson 37/80
- 4 min
Learn client-side page transitions with React Router.
What is React Router?
React Router is a library that manages page transitions in a single page app (SPA). When the URL changes, the relevant component renders without a page reload.
In a normal site, every link reloads the whole page. In an SPA, only the URL changes and React Router renders the relevant component. This gives a fast and smooth experience.
The skeleton: wrap the app with <BrowserRouter>, define <Route path="/" element={ '{ <Home /> }' } /> inside <Routes>. Use <Link to="/about"> for navigation.
Three core components
React Router has three core components: BrowserRouter (wraps the app), Routes (routes container), Route (a single route definition).
<BrowserRouter> is at the top; it wraps the whole app. <Routes> contains multiple <Route>s; one is selected based on the URL.
For navigation, use <Link to="...">. Prefer Link over <a href>; because a reloads the page, Link only changes the URL.
Practice Router skeleton
Complete the skeleton. Write an App component. Inside <BrowserRouter>, define <Routes> with one <Route path="/" element={ '{ <Home /> }' } />. Export it. (Assume BrowserRouter, Routes, Route, Home are imported.)
Starter code
// Write the App component hereSample solution
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</BrowserRouter>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does React Router manage?
- useEffect
- Page transitions Correct answer
- CSS
- useState
Explanation: Manages page transitions.
2 SPA
SPA stands for ____.
SPA stands for Single Page Application.
Explanation: SPA = Single Page Application.
3 Match the router parts
| Term | Meaning |
|---|---|
BrowserRouter |
wraps |
Routes |
container |
Route |
single route |
Link |
navigation |