23) Routes and Route in React
In React routing (using React Router), Routes and Route are the core building blocks that decide which component should render for a given URL.
Think of them like a traffic control system:
i) Routes → the controller (decides which route matches)
ii) Route → individual rules (maps path → component)What is Routes
Routes is a wrapper component that,
i) Looks at the current URL
ii) Finds the best matching
iii) Route Renders only that matched routeimport { Routes, Route } from "react-router-dom"; const App = () => { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> ); }Here, If URL =
/aboutOnly<About />rendersWhat is Route
Route defines: “If URL matches this path → render this component”<Route path="/path" element={<Component />} />When user visits
/contactthen<Contact />is rendered<Routes> <Route path="/" element={<Home />} /> <Route path="/products" element={<Products />} /> </Routes>User visits
/products
Routes checks all Route
Finds match →/products
Renders<Products />
Only ONE route renders - Unlike older versions (Switch), Routes picks the best match.Example
import { BrowserRouter, Routes, Route, Link } from "react-router-dom"; const App = () => { return ( <BrowserRouter> <nav> <Link to="/">Home</Link> | <Link to="/about">About</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/user/:id" element={<User />} /> </Routes> </BrowserRouter> ); }Dynamic Routes
<Route path="/user/:id" element={<User />} /> // /user/101import { useParams } from "react-router-dom"; const User = () => { const { id } = useParams(); return <h2>User ID: {id}</h2>; }Nested Routes
<Routes> <Route path="/dashboard" element={<Dashboard />}> <Route path="profile" element={<Profile />} /> <Route path="settings" element={<Settings />} /> </Route> </Routes>// UR /dashboard/profile /dashboard/settings