Script Valley
React.js: Complete Course
React Router and NavigationLesson 5.2

Dynamic routes and URL parameters in React Router

route params with :id, useParams hook, query strings, useSearchParams, nested routes, Outlet component, index routes

Dynamic Routes and Parameters

Dynamic segments in route paths (prefixed with :) capture values from the URL. useParams gives you access to these values inside the matched component.

URL Parameters

// Route definition
<Route path="/products/:productId" element={<ProductDetail />} />

// Inside ProductDetail
import { useParams } from 'react-router-dom';

function ProductDetail() {
  const { productId } = useParams();

  return <h1>Product ID: {productId}</h1>;
}

Query Strings

import { useSearchParams } from 'react-router-dom';

function Search() {
  const [searchParams, setSearchParams] = useSearchParams();
  const query = searchParams.get('q') || '';

  return (
    <input
      value={query}
      onChange={e => setSearchParams({ q: e.target.value })}
    />
  );
}
// URL: /search?q=react

Nested Routes with Outlet

<Route path="/dashboard" element={<DashboardLayout />}>
  <Route index element={<Overview />} />
  <Route path="settings" element={<Settings />} />
</Route>

// DashboardLayout.jsx
function DashboardLayout() {
  return (
    <div>
      <Sidebar />
      <Outlet /> {/* child routes render here */}
    </div>
  );
}

Up next

Protected routes and authentication in React Router

Sign in to track progress