Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if route matches a pattern with React-Router v4?

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`
)
like image 783
SimpleJ Avatar asked Jun 11 '18 20:06

SimpleJ


People also ask

How do you know if a route matches react?

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, });

Which property will you set on the route to match with the URL?

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)

Which element tries to match its path to the current history location in react?

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.


1 Answers

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

like image 127
Jimubao Avatar answered Sep 28 '22 08:09

Jimubao