How to check if generic react-router path matches current location pathname?
react-router path: /Movies/:id
location.pathname: /Movies/56fa7446bae6eb301e5937f3
I want to use route paths with menu buttons, to set class="active".
EDIT:
To clarify, paths in my app look like:
/Movies/56fa7/watch
and not like:
/Movies/watch/56fa7
How do I check if the former route is active?
Is it doable without <Link>
component?
/Movies/56fa7/watch
is arbitrary after /Movies
, and <Link>
obviously can't be pointed to an arbitrary location. So let's ignore <Link>
for a moment:
Is there a standalone function or property in react-router that checks if /Movies/:id/watch
is active?
According to the docs, you could use matchPath
function which takes two arguments:
String
). Object
) or path (String
) to match against.If matched it will return an object of this shape:
{
path, // the path used to match
url, // the matched portion of the URL
isExact, // whether or not we matched exactly
params
}
Otherwise you'll get null
.
To make use of it in your components you could simply do:
import { matchPath } from 'react-router';
// ...
render () {
const isMovieWatchPathActive = !!matchPath(
this.props.location.pathname,
'/Movies/:id/watch'
);
// ...
}
Hope it'll help someone.
I'm a bit late to the party, but hopefully this will help anyone with the same question. When a component is rendered through a Route
, certain props are passed to it. These props can be used to determine which route is active.
In a component rendered by a Route
, you can use this.props.match.url
to get the actual URL requested by the browser, and you can use this.props.match.path
to get the path pattern for the current route.
Check working example here: https://codesandbox.io/s/20o7q0483j
Docs related to this are available here: https://reacttraining.com/react-router/web/api/Route/Route-props
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With