Tuesday, June 24, 2025

thumbnail

How to Use URL Parameters in React Router

 ๐ŸŒ How to Use URL Parameters in React Router (v6+)

URL parameters (also called route parameters) allow you to pass dynamic values through the URL in a React app. These are very useful when building detail pages like /user/123 or /product/42.


๐Ÿ“ฆ Step-by-Step Guide

✅ 1. Install React Router (if you haven’t already)

bash

Copy

Edit

npm install react-router-dom

✅ 2. Define a Route with a Parameter

In your routing setup (usually in App.js or routes.js):


jsx

Copy

Edit

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

import Home from './Home';

import UserProfile from './UserProfile';


function App() {

  return (

    <BrowserRouter>

      <Routes>

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

        <Route path="/user/:id" element={<UserProfile />} />

      </Routes>

    </BrowserRouter>

  );

}


export default App;

๐Ÿ“ :id is a URL parameter that will change based on the user.


✅ 3. Access the URL Parameter Inside a Component

In UserProfile.js:


jsx

Copy

Edit

import React from 'react';

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


function UserProfile() {

  const { id } = useParams(); // get the "id" from the URL


  return (

    <div>

      <h2>User Profile</h2>

      <p>User ID: {id}</p>

    </div>

  );

}


export default UserProfile;

๐ŸŽฏ useParams() gives you an object with all the route parameters.


✅ 4. Navigate to the Route with Parameters

You can link to a specific user profile like this:


jsx

Copy

Edit

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


<Link to="/user/123">View User 123</Link>

Or programmatically using useNavigate():


jsx

Copy

Edit

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


const navigate = useNavigate();

navigate('/user/123');

๐Ÿง  Use Cases for URL Parameters

/post/:postId → Blog post detail page


/product/:productId → Product detail


/category/:name/page/:pageNum → Paginated categories


✅ Summary

Step What to Do

1️⃣ Define route with :paramName

2️⃣ Use useParams() to access the value

3️⃣ Link to the route using <Link to="/path/value">

Learn React JS Course in Hyderabad

Read More

Programmatic Navigation in React

Nested Routes in React Explained

Setting Up React Router (v6)

๐ŸŒ React Router & Navigation

Visit Our Quality Thought Training in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive