Reputation: 14768
How can I check if a route pattern matches the current route using React Router v4 without the Route
or NavLink
components or writing my own regex to match against the route?
For example, if the route is /users/5/friends/3/pets/10/edit
, I want to be able to check if the route matches a pattern (like the one used by Route
and NavLink
). Something like this:
const isEditFriendPetRoute = routeMatches('/users/:userId/friends/:friendId/pets/:petId/edit');
console.log(
isEditFriendPetRoute
? `Is editing friend's pet`
: `Is not editing friends pet`
)
Upvotes: 6
Views: 7627
Reputation: 411
import { matchPath } from 'react-router-dom'
const match = matchPath('/users/123', {
path: '/users/:id',
exact: true,
strict: false
})
If the URL is matched with the path pattern then it will return an object, else it will return null.
Check the api from the following page https://reacttraining.com/react-router/web/api/matchPath
Upvotes: 10