Thuta Learning
AdvancedWeb Developmentintermediate

URL Parameters

Relax. We'll talk through this in plain words — no textbook voice.

A URL parameter is a variable value inside a URL that a route captures. For example, in `/products/15`, `15` could be a product id, and in `/users/sai`, `sai` could be a username.

jsx
import { BrowserRouter, Routes, Route, useParams } from 'react-router-dom';

function UserProfile() {
  const { userId } = useParams();
  return <h2>User Profile ID: {userId}</h2>;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/users/:userId" element={<UserProfile />} />
      </Routes>
    </BrowserRouter>
  );
}

Since the route path is written as `:userId`, visiting `/users/123` sets `userId` to `123`.

You should see
At the URL `/users/123`, it shows `User Profile ID: 123`.

Info

`useParams()` always returns string values. If you need a number, convert it wherever you need it.

Easy traps

  • If the route parameter name doesn't match the name you destructure, you won't get the value. For `:userId`, destructure it as `{ userId }`.
URL Parameters | Thuta Learning