Routing with React Router
React Router Setup
React has no built-in router. React Router is the de facto standard: you install react-router-dom, wrap the app in a router, and declare which component renders for each URL path.
What is Router Setup in React?
React has no built-in router. React Router is the de facto standard: you install react-router-dom, wrap the app in a router, and declare which component renders for each URL path.
Why Router Setup matters
A single-page app must change what is on screen without a full page reload, keep the browser URL in sync, and make the back button work. That is exactly what a router provides.
Router Setup example
npm install react-router-domDeclaring routes
import { BrowserRouter, Routes, Route } from 'react-router-dom';
export default function App() {
return (
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/internships" element={<JobList />} />
<Route path="/internships/:id" element={<JobDetail />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}BrowserRouter uses the HTML5 history API to give clean URLs. Routes picks the single best match, and path="*" catches everything unmatched as a 404 page. Anything outside Routes — the Navbar here — renders on every page.
Key points to remember
- Only one router component should wrap the whole app.
- Use HashRouter only when you cannot configure the server for clean URLs.
- A production deployment must rewrite unknown paths to index.html, or a refresh on /internships returns a server 404.
Common mistakes with Router Setup
- Using <a href> for internal navigation, which triggers a full page reload and loses app state.
- Forgetting the server rewrite rule, so direct links and refreshes 404.
React Router Setup— Interview Questions & FAQs
Why does refreshing a route give a 404 on my server?+
The browser asks the server for /internships, which does not exist as a file. Configure the host to serve index.html for any unmatched path — a _redirects file on Netlify, a rewrite in vercel.json, or try_files in Nginx.
