Wednesday, 22 January 2025

Dynamic Routes in React Router: Passing and Accessing URL Parameters

In modern web applications, dynamic routing is an essential feature, allowing you to create flexible routes based on variables such as user IDs, product names, or categories.

With React Router, you can easily pass dynamic parameters through URLs and access them within your components to render personalized content. In this post, we will explore how to pass dynamic parameters (like /user/:id) in the URL, access them using the useParams hook, and build a dynamic profile page.

 

1. Passing Dynamic Parameters through the URL (e.g., /user/)

Dynamic parameters in URLs allow you to model your application based on user input or backend data. In React Router, you define a route with a dynamic parameter using the colon (:) syntax.

 

For example, /user/:id means that :id is a dynamic part of the URL that can change depending on the user being viewed.

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

 

Here, we define a route /user/:id, where :id represents a dynamic parameter that can hold different values (e.g., /user/123 or /user/456). The component UserProfile will use this parameter to display the corresponding user's data.

 

2. Accessing Route Parameters Using the useParams Hook

React Router provides the useParams hook to access these dynamic parameters from the URL. This hook returns an object containing all the parameters defined in the route. You can then use these parameters inside your component to fetch or display personalized content.

 

Example

 

const { id } = useParams(); // Access the dynamic parameter "id"

 

In this example, the useParams hook extracts the id parameter from the URL (e.g., if the URL is /user/123, id will be 123). You can then use the id to fetch the corresponding user data from an API or database.

 

Follow below step-by-step buide to build the complete working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘url-parameters-demo’.

 

Project structure looks like below.

 


 

Step 2: Navigate to the project directory and install react router dom by executing below commands. 

cd url-parameters-demo
npm install react-router-dom

 

Step 3: Create pages folder in src folder, and define UserProfile and UserSearch components.

 

UserProfile.jsx

 

import { Link, useParams } from "react-router-dom";

let users = [
  { id: "1", name: "Krishna", age: 36 },
  { id: "2", name: "Ram", age: 39 },
];

function getUser(id) {
  for (let user of users) {
    if (user.id === id) {
      return user;
    }
  }

  return undefined;
}

export default function UserProfile() {
  const { id } = useParams();
  let user = getUser(id);

  if (user === undefined) {
    return (
      <>
        <h3>User details not found</h3>
        <Link to="/">Click here to search users</Link>
      </>
    );
  }

  return (
    <>
      <h3>User Details</h3>
      <ul>
        <li>Id: {user.id}</li>
        <li>Name: {user.name}</li>
        <li>Age: {user.age}</li>
      </ul>
      <br />
      <Link to="/">Click here to search users</Link>
    </>
  );
}

 

UserSearch.jsx

import { useState } from "react";
import { useNavigate } from "react-router-dom";

export default function UserSearch() {
  const [userId, updateUserId] = useState(1);
  const navigate = useNavigate();

  return (
    <>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          let url = "/user-profile/" + userId;
          navigate(url);
        }}
      >
        <label htmlFor="userId">Enter User Id</label> &nbsp;&nbsp;
        <input
          type="text"
          placeholder="userId"
          value={userId}
          onChange={(event) => {
            updateUserId(event.target.value);
          }}
        />
        <br />
        <br />
        <button>Fetch User Details</button>
      </form>
    </>
  );
}

 

Step 4: Update App.jsx with below content.

 

App.jsx

import { useState } from "react";
import { BrowserRouter, Route, Routes, Link } from "react-router-dom";
import UserSearch from "./pages/UserSearch";
import UserProfile from "./pages/UserProfile";

function App() {
  const [count, setCount] = useState(0);

  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/user-profile/:id" element={<UserProfile />} />
          <Route path="/" element={<UserSearch />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;

 

Step 5: Update main.jsx with below content.

 

main.jsx

 

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

 

Step 6: Build and run the application by executing below commands.

  cd url-parameters-demo
  npm install
  npm run dev

Open the url ‘http://localhost:5173/’ in browser, you will see below screen.


 


Enter the user id (For ex: 1) and click on the button ‘Fetch User Details’, you will see the user details like below.

 


You can download the application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment