Module: Routing

URL Parameters

React JS: Routing - URL Parameters

URL parameters (also known as route parameters) allow you to capture dynamic segments of a URL and use them within your component. This is crucial for creating dynamic routes like user profiles, product details, or blog posts. React Router provides a straightforward way to handle these.

1. Defining Routes with Parameters

You define routes with parameters using the :paramName syntax in your Route path.

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/users/:userId" element={<UserProfile />} />
        <Route path="/products/:productId" element={<ProductDetails />} />
        <Route path="/blog/:year/:month/:slug" element={<BlogPost />} />
      </Routes>
    </Router>
  );
}

export default App;

In these examples:

  • /users/:userId: Captures a user ID.
  • /products/:productId: Captures a product ID.
  • /blog/:year/:month/:slug: Captures the year, month, and slug of a blog post.

2. Accessing Parameters in Components

You access these parameters using the useParams hook from react-router-dom.

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

function UserProfile() {
  const { userId } = useParams();

  return (
    <div>
      <h1>User Profile</h1>
      <p>User ID: {userId}</p>
      {/* Fetch user data based on userId */}
    </div>
  );
}

export default UserProfile;

useParams() returns an object where the keys are the parameter names defined in your route path (e.g., userId, productId, year, month, slug), and the values are the corresponding segments from the URL.

3. Example: Product Details

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

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

  // Simulate fetching product data
  const product = {
    id: productId,
    name: `Product ${productId}`,
    description: `Details for product with ID ${productId}`
  };

  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.description}</p>
    </div>
  );
}

export default ProductDetails;

If the URL is /products/123, productId will be "123".

4. Type Considerations

The values returned by useParams() are always strings. If you need a number, you'll need to convert it:

const { userId } = useParams();
const userIdNumber = parseInt(userId, 10); // Convert to integer

Always include a radix (the second argument to parseInt) to avoid unexpected behavior.

5. Optional Parameters (React Router v6.4+)

React Router v6.4 introduced support for optional parameters using ? after the parameter name.

<Route path="/users/:userId?" element={<UserProfile />} />

Now, /users and /users/123 will both match this route. Inside UserProfile, userId will be undefined if the parameter is not present in the URL.

function UserProfile() {
  const { userId } = useParams();

  return (
    <div>
      <h1>User Profile</h1>
      {userId ? <p>User ID: {userId}</p> : <p>No user ID specified.</p>}
    </div>
  );
}

6. Nested Routes with Parameters

You can combine parameters with nested routes.

<Route path="/categories/:categoryId/products/:productId" element={<ProductDetails />} />

In this case, useParams() will return an object containing both categoryId and productId.

7. Using Link with Parameters

When creating links to routes with parameters, you can use template literals or object notation.

Template Literals:

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

function UserList({ users }) {
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>
          <Link to={`/users/${user.id}`}>{user.name}</Link>
        </li>
      ))}
    </ul>
  );
}

Object Notation:

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

function UserList({ users }) {
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>
          <Link to={{ pathname: `/users/${user.id}` }}>{user.name}</Link>
        </li>
      ))}
    </ul>
  );
}

Object notation is useful when you need to pass additional state along with the route.

Summary

URL parameters are a powerful feature of React Router that enable you to create dynamic and flexible web applications. By understanding how to define routes with parameters and access them using useParams, you can build complex routing structures that meet the needs of your application. Remember to handle data type conversions and consider optional parameters when appropriate.