Routing allows your React application to switch between different UI pages without reloading the browser. Instead of loading new HTML files, React simply changes components based on the URL.
It wraps your entire app and tells React Router to enable routing. Think of it as: “Enable URL-based navigation”.
import { BrowserRouter } from "react-router-dom";
<BrowserRouter>
<App />
</BrowserRouter>
A container that holds all your Route components.
Used to define which component should load on which URL.
<Routes>
<Route path="/about" element={<About />} />
</Routes>
path and element?They are props (like HTML attributes) of the <Route /> component.
Defines which URL should load the component.
Defines which component should appear.
<Route path="/contact" element={<Contact />} />
element instead of component?Old versions used:
<Route component={Home} />
But this caused unnecessary re-renders and made it difficult to pass props. Now React Router expects:
<Route element={<Home />} />
This gives:
Dynamic routing means the URL can contain variables.
<Route path="/user/:id" element={<UserProfile />} />
Retrieve the id using useParams:
import { useParams } from "react-router-dom";
const UserProfile = () => {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
};
This is used for dashboards, layouts, or sections.
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
Inside Dashboard:
import { Outlet } from "react-router-dom";
const Dashboard = () => (
<div>
<Sidebar />
<Outlet /> {/* Nested pages appear here */}
</div>
);
Used for Login-based pages.
import { Navigate } from "react-router-dom";
const PrivateRoute = ({ element }) => {
const isLoggedIn = localStorage.getItem("token");
return isLoggedIn ? element : <Navigate to="/login" />;
};
<Route
path="/dashboard"
element={<PrivateRoute element={<Dashboard />} />}
/>
import { lazy, Suspense } from "react";
const About = lazy(() => import("./About"));
<Suspense fallback={<h1>Loading...</h1>}>
<Route path="/about" element={<About />} />
</Suspense>
React only loads the component when needed → improves performance.