Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I match if the current route matches a pattern in React Router Dom v6?

I’ve got:

export const ACCOUNT_PORTAL_PATHS = [
      'home/*',
      'my-care/*',
      'chats/*',
      'profile/*',
      'programs/*',
      'completion/*',
    ]

If the current path is any of those, I want to know. I managed to get the current path with:

const { search: searchParams, pathname } = useLocation();

and that yields, in this example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pathname: "/my-care/1234"

What’s the best way to match?

Thanks in advance!

>Solution :

If you just want to know if you are on a matching path, you can use the matchPath function and test that some account path prefix is a match to the current pathname.

Example:

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

...

const { pathname } = useLocation();
const isMatch = ACCOUNT_PORTAL_PATHS.some((path) =>
  matchPath(path, pathname)
);

Edit epic-shtern-gyuolz

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading