npm install react-router-domimport { BrowserRouter, Routes, Route, Link } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}<BrowserRouter>: wraps the whole app, enabling routing<Link>: replaces<a>tags โ navigates without a full page reload<Routes>/<Route>: maps a URL path to the component that should render there
<Routes>
<Route path="/courses" element={<CourseList />} />
<Route path="/courses/:courseId" element={<CourseDetail />} />
</Routes>
import { useParams } from "react-router-dom";
function CourseDetail() {
const { courseId } = useParams();
return <p>Showing course #{courseId}</p>;
}The :courseId segment is a dynamic parameter โ visiting /courses/42 renders CourseDetail with useParams() giving you { courseId: "42" }.
import { Navigate, useNavigate } from "react-router-dom";
function ProtectedRoute({ isLoggedIn, children }) {
if (!isLoggedIn) {
return <Navigate to="/login" />;
}
return children;
}
function LoginButton() {
const navigate = useNavigate();
function handleLogin() {
// ...perform login...
navigate("/dashboard");
}
return <button onClick={handleLogin}>Login</button>;
}<Navigate> redirects declaratively (useful for guarding routes), while useNavigate() lets you redirect imperatively from inside event handlers, like after a successful login.
A normal <a href="/about"> triggers a full browser page reload, throwing away your entire React app's state and defeating the purpose of a single-page application. Always use <Link> (or <NavLink> for active-state styling) for internal navigation instead.
Set up basic routing for a three-page site: Home, About, and a Contact page with a route parameter for a department name.
import { BrowserRouter, Routes, Route, Link, useParams } from "react-router-dom";
function Home() { return <h2>Home Page</h2>; }
function About() { return <h2>About Page</h2>; }
function Contact() {
const { dept } = useParams();
return <h2>Contact: {dept}</h2>;
}
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact/sales">Contact Sales</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact/:dept" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}
Q What's the difference between Link and NavLink?
Link is the basic navigation component. NavLink does everything Link does, plus automatically applies an 'active' styling class when its target route matches the current URL โ ideal for nav bar highlighting.
Q Do I need a separate backend server to use React Router?
No โ React Router handles routing entirely on the client side, within the single HTML page your React app loads into. It doesn't require any server-side routing configuration for a typical single-page app deployment.