How to check if a React Router path is active?

Sometimes, we want to check if a React Router path is active.

In this article, we’ll look at how to check if a React Router path is active.

How to check if a React Router path is active?

To check if a React Router path is active, we can use the matchPath function.

For instance, we write

import { matchPath } from "react-router";

const match = matchPath("/users/123", {
  path: "/users/:id",
  exact: true,
  strict: false,
});

to call matchPath with a URL and an object with the URL properties from the location object.

It returns true if it matches and false otherwise.

Conclusion

To check if a React Router path is active, we can use the matchPath function.