Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Router V6 check if path matches a pattern

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
like image 206
ghophri Avatar asked Jan 02 '26 08:01

ghophri


1 Answers

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 });
like image 64
amrinea Avatar answered Jan 05 '26 21:01

amrinea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!