How to pass parameters to component with React Router?

Sometimes, we want to pass parameters to component with React Router.

In this article, we’ll look at how to pass parameters to component with React Router.

How to pass parameters to component with React Router?

To pass parameters to component with React Router, we can use the useParams hook.

For instance, we write

<Route path="/details/:id" component={DetailsPage} />;

to add the id parameter to our route.

Then in DetailsPage, we write

import { useParams } from 'react-router';

export default function DetailsPage() {
  const { id } = useParams();
  // ...
}

to call the useParmas hook and get the id property from the returned object to get the value of the id URL parameter.

Conclusion

To pass parameters to component with React Router, we can use the useParams hook.