13

I'm trying to check a "/admin/posts/new" to "/admin/*" in react-router v6. I found that there is a matchRoutes function

import { useLocation } from "react-router";
const { pathname } = useLocation();
const isAdminPath = someMatchFunc(pathname,"/admin/*") <<<< something goes here returns true or null
ghophri
  • 183
  • 1
  • 1
  • 12

2 Answers2

14

You should be able to use the matchPath function. It would look something like this in v6:

import { useLocation, matchPath } from "react-router";
const { pathname } = useLocation();
const isAdminPath = matchPath("/admin/*", pathname);

It's important to note that they changed the parameters in v6. In v5, you would have done something like this instead.

import { useLocation, matchPath } from "react-router";
const { pathname } = useLocation();
const isAdminPath = matchPath(pathname, { path: "/admin", exact: false });
amrinea
  • 553
  • 4
  • 12
  • 1
    But matchPath is not considering the basename. what we need to add inorder to match the path along with basename. – Monish N Dec 31 '21 at 07:14
  • @MonishN - The original question didn't say anything about needing to match basename. – amrinea Feb 08 '22 at 14:09
0

Use useRouteMatch instead matchPath

import { useRouteMatch } from "react-router-dom";

function BlogPost() {
  let match = useRouteMatch("/blog/:slug");

  // Do whatever you want with the match...
  return <div />;
}
Rameshkumar
  • 264
  • 1
  • 12
  • If you need to see if child routes are there, you can use `*` e.g. `let match = useRouteMatch("/blog/:slug/*")` which would return `match.params['*']` as a string of anything matching. For example `/blog/hello/edit` would be `{ slug: 'hello', '*': 'edit' }`. – knownasilya Feb 03 '22 at 15:23
  • 2
    This only works for react router v5 as `useRouteMatch` isn't exported in v6. – technogeek1995 Sep 07 '22 at 13:27