How to get URL parameters in component in React Router?

Sometimes, we want to get URL parameters in component in React Router v4.

In this article, we’ll look at how to get URL parameters in component in React Router v4.

How to get URL parameters in component in React Router v4?

To get URL parameters in component in React Router v4, we can use the useParams hook.

For instance, we write

<Route path="/:id" children={<Child />} />

to add a Route with the children prop set to Child to render it if we go to /:id.

:id is the placeholder for the id route parameter.

Then in Child, we write

const { id } = useParams();

to call the useParams hook to return an object with the URL parameters.

And we can get the value of the :id with id.

Conclusion

To get URL parameters in component in React Router v4, we can use the useParams hook.