0
0
Reactframework~5 mins

Route parameters in React

Choose your learning style9 modes available
Introduction

Route parameters let your app get information from the URL. This helps show different content based on what the user clicks or types.

Showing a user profile page based on the user ID in the URL.
Displaying details of a product when clicking on it in a list.
Navigating to a blog post page using the post's unique ID.
Filtering content by category or tag from the URL.
Creating dynamic pages where the content changes with the URL.
Syntax
React
import { useParams } from 'react-router-dom';

function Component() {
  const params = useParams();
  // Access params.id or other keys
  return <div>{params.id}</div>;
}

useParams is a React hook from react-router-dom that reads parameters from the URL.

Route parameters are defined in the route path with a colon, like /user/:id.

Examples
This example gets the id parameter from the URL and shows it.
React
import { useParams } from 'react-router-dom';

function User() {
  const { id } = useParams();
  return <h1>User ID: {id}</h1>;
}
Here, the route expects a productId parameter to display product details.
React
import { useParams } from 'react-router-dom';

function Product() {
  const { productId } = useParams();
  return <p>Product number: {productId}</p>;
}
You can also get all parameters as an object and access them by name.
React
import { useParams } from 'react-router-dom';

function Post() {
  const params = useParams();
  return <div>Post slug: {params.slug}</div>;
}
Sample Program

This app has a home page with links to two user profiles. Clicking a link changes the URL with a user ID. The UserProfile component reads that ID from the URL and shows it.

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

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

function Home() {
  return (
    <div>
      <h1>Home</h1>
      <nav>
        <ul>
          <li><Link to="/user/101">User 101</Link></li>
          <li><Link to="/user/202">User 202</Link></li>
        </ul>
      </nav>
    </div>
  );
}

export default function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/user/:userId" element={<UserProfile />} />
      </Routes>
    </Router>
  );
}
OutputSuccess
Important Notes

Route parameters are always strings. Convert them if you need numbers.

If a parameter is missing, useParams() returns undefined for it.

Use semantic HTML and accessible links for better user experience.

Summary

Route parameters let your app read values from the URL to show dynamic content.

Use useParams() hook inside components to get these values.

Define parameters in route paths with a colon, like /user/:id.