What is React Router?
By default, React is a single-page application framework. That means when you navigate, the entire page reloads. Not great for user experience. React Router fixes that.
Think of React Router as a traffic controller for your app. It watches the URL in the browser and decides which components to show โ without ever refreshing the page.
It gives you that smooth, app-like experience where navigation feels instant. Your users click a link and boom โ new content, no white flash, no loading spinner.
Setting Up React Router
Getting started is straightforward. Install the package and wrap your app in a router component.
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>
);
}
BrowserRouter is the most common router. It uses the browser's history API to keep your URLs clean and readable. No ugly hash symbols in the URL.
Inside BrowserRouter, you define Routes, and each Route maps a URL path to a component. Simple as that.
Try it Yourself โRoute Components
The Route component is the bread and butter of React Router. It takes two main props: path and element.
The path prop defines which URL matches this route. The element prop is the component that renders when the path matches. You can also add wildcards and optional parameters to your paths.
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users/:id" element={<UserProfile />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
That star route at the bottom is your catch-all. If none of the other routes match, it renders the NotFound component. Always have a catch-all โ your users will appreciate the friendly 404 page.
The Link Component
Never use regular anchor tags for navigation in a React app. They cause full page reloads, which defeats the whole purpose of a single-page application.
import { Link } from "react-router-dom";
function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}
Link works just like an anchor tag for the user โ they can right-click and open in new tab, middle-click to open in a new tab, all that good stuff. But under the hood, it handles navigation client-side without a page reload.
You can also add className props for styling, and React Router will automatically add an active class when the current URL matches the link's destination.
Try it Yourself โ