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`
)
To check if a React Router path is active, we can use the matchPath function. import { matchPath } from "react-router"; const match = matchPath("/users/123", { path: "/users/:id", exact: true, strict: false, });
A match object contains information about how a <Route path> matched the URL. match objects contain the following properties: params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path. isExact - (boolean) true if the entire URL was matched (no trailing characters)
A <Route> element tries to match its path to the current history location (usually the current browser URL). However, a location with a different pathname can also be passed for matching.
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
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