How to Get Path Params in React Router?

Sometimes, we want to get path params in React Router.

In this article, we’ll look at how to get path params in React Router.

Get Path Params in React Router

To get path params in React Router, we can use the useParams hook.

For instance, we write:

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

const Child = () => {
  const { id } = useParams();

  return (
    <div>
      <h3>ID: {id}</h3>
    </div>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <h2>Accounts</h2>

        <ul>
          <li>
            <Link to="/1">foo</Link>
          </li>
          <li>
            <Link to="/2">bar</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/:id/" children={<Child />} />
        </Switch>
      </div>
    </Router>
  );
}

We create the Child component that calls the useParams hook to return an object with the route params in the URL.

And we render the value of the id param on the page.

In App, we have 2 links that goes to routes with different id param values.

To render Child when we click on the link, we add the Route in the Switch component.

And we set the path to /:id/. and children to Children.

:id is the route param placeholder, so id will be returned in useParams.

Conclusion

To get path params in React Router, we can use the useParams hook.