Shamoon
Shamoon

Reputation: 43617

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:

pathname: "/my-care/1234"

What's the best way to match?

Thanks in advance!

Upvotes: 10

Views: 4979

Answers (1)

Drew Reese
Drew Reese

Reputation: 203587

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

Upvotes: 2

Related Questions