Categories
React Answers

How to pass parameters to component with React Router?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *