Skip to main content

Command Palette

Search for a command to run...

23) Routes and Route in React

Updated
View as Markdown
  1. 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)

  2. 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 route

    import { Routes, Route } from "react-router-dom";
    
    const App = () => {
      return (
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      );
    }
    

    Here, If URL = /about Only <About /> renders

  3. What is Route
    Route defines: “If URL matches this path → render this component”

    <Route path="/path" element={<Component />} />
    

    When user visits /contact then <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.

  4. 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>
      );
    }
    
  5. Dynamic Routes

    <Route path="/user/:id" element={<User />} />
    
    // /user/101
    
    import { useParams } from "react-router-dom";
    
    const User = () => {
      const { id } = useParams();
      return <h2>User ID: {id}</h2>;
    }
    
  6. 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