DEV Community

PRIYA K
PRIYA K

Posted on

useParams in React

https://www.geeksforgeeks.org/reactjs/reactjs-useparams-hook/
https://reactrouter.com/api/hooks/useParams
http://refine.dev/blog/react-router-useparams/

  • Is a React Hook
  • Allows to access dynamic values from URL in React Router.
  • Helps render content based on route parameters like /user/:id
  • Exact parameters directly from URL
  • Enable dynamic routing and data display
  • used to fetch or show user-specific content
  • Returns an object of key/value pairs of the dynamic params from current URL,matches by the route
  • Child route inherit all params from parent route
  • route pattern like /posts/:postId is matched by /posts/123 then params.postId will be "123".
  • dynamic rendering of content depending on the URL.
  • available in React router since version 5.
  • use it to retrieve route parameters from the component rendered by the matching route.
  • To retrieve route parameters from the functional component rendered by the matching route.
  • The React Router useParams hook returns an object whose keys are the parameter names declared in the path string in the Route definition, and the values are the corresponding URL segment from the matching URL.

Syntax

const { param1, param2, ... } = useParams();
Enter fullscreen mode Exit fullscreen mode

param1, param2, etc., are route parameters defined in the path.
useParams returns an object where keys are the parameter names and values are the values from the URL

Returns
An object containing the dynamic route parameters
import { useParams } from "react-router";

Examples

// given a route like:
<Route path="/posts/:postId" element={<Post />} />;
// or a data route like:
createBrowserRouter([
  {
    path: "/posts/:postId",
    component: Post,
  },
]);
// or in routes.ts
route("/posts/:postId", "routes/post.tsx");
Enter fullscreen mode Exit fullscreen mode

Access the params in a component

import { useParams } from "react-router";

export default function Post() {
  let params = useParams();
  return <h1>Post: {params.postId}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Multiple Params
Patterns can have multiple params:

"/posts/:postId/comments/:commentId";
Enter fullscreen mode Exit fullscreen mode

All will be available in the params object:

import { useParams } from "react-router";

export default function Post() {
  let params = useParams();
  return (
    <h1>
      Post: {params.postId}, Comment: {params.commentId}
    </h1>
  );
}
Enter fullscreen mode Exit fullscreen mode

Catchall Params
Catchall params are defined with *:

"/files/*";
Enter fullscreen mode Exit fullscreen mode

The matched value will be available in the params object as follows:

import { useParams } from "react-router";
export default function File() {
  let params = useParams();
  let catchall = params["*"];
  // ...
}
Enter fullscreen mode Exit fullscreen mode

You can destructure the catchall param:

export default function File() {
  let { "*": catchall } = useParams();
  console.log(catchall);
}

Enter fullscreen mode Exit fullscreen mode

useParams is called inside the BlogPost component to fetch the dynamic parameter id from the URL.
The URL /post/:id means that the value for id is dynamically passed and can be accessed via useParams

Route parameters obtained using useParams() may sometimes be missing or invalid.

It is recommended to validate them (e.g., check for undefined or correct format) before using.

In such cases, you can show a fallback UI or redirect the user to a safe route.

Setting up React Router

Step 1 - Install React Router

# Using NPM
npm install react-router-dom@6
Enter fullscreen mode Exit fullscreen mode

Step 2 - How to set up React router
To use React router in the browser environment, import BrowserRouter and wrap your root component as in the example below. BrowserRouter is a top-level Component. Other routers, such as NativeRouter and StaticRouter, have their use cases you can look up in the documentation.

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>,
);
Enter fullscreen mode Exit fullscreen mode

Step 3 - How to set up routes
Unlike in earlier versions of React router, you import the Routes and Route components in React router version 6 .

import { Route, Routes } from "react-router-dom";
import { Home, Blog } from "./components";

function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/blog" element={<Blog />} />
      </Routes>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

What are URL parameters in React router
In React Router, parameters are like placeholders (variables).
In JavaScript, function parameters (like a, b) are placeholders, and values you pass (like 2, 3) are arguments.
Same idea is used in URLs โ†’ React Router has URL parameters.

Example: /blog/:id โ†’ here id is a placeholder (URL parameter).
Enter fullscreen mode Exit fullscreen mode

The : means the value can change dynamically.
So /blog/use-params will match /blog/:id.
Here, id = "use-params" inside the Blog component.
React Router automatically extracts this value from the URL.
You can access it using the useParams hook inside your component.

How to use the useParams hook
In React Router, you define a route with a URL parameter like /blog/:id.
This helps you use the same component for different URLs.
Inside your component, you use the useParams hook to get the value from the URL.
useParams() returns an object with parameter names and their values.
Example: if URL is /blog/use-params, then it returns { id: "use-params" }.
You can then use this id value inside your component as needed.

Using Nested Routes with useParams
Validating URL Parameters

Question
1.What does the useParams hook return when used inside a component?
Answer:
An object containing keyโ€“value pairs of URL parameters

Top comments (0)