Home > Mobile >  React router dom v6 matchPatch is not working
React router dom v6 matchPatch is not working

Time:02-03

I am using react router dom v6, and I would like to match a path with current url.

this is the path I would like to check. :workspaceMasterStoreDataId?/account/:masterDataAccountId/list

this is what useMatches return so the current location :

params:{workspaceMasterStoreDataId: '1031', masterDataAccountId: '12'}
pathname:"/1031/account/12/list"

I would like to check if my path match or not.

I tried many ways

  const test = matchPath(":workspaceMasterStoreDataId?/account/:masterDataAccountId/list", pathname);
  const tests = matchPath(
    `:workspaceMasterStoreDataId/account/:masterDataAccountId/list`,
    pathname
  );
  const test3s = matchPath(
    `/:workspaceMasterStoreDataId?/account/:masterDataAccountId/list`,
    pathname
  );
  const test33s = matchPath(
    `/:workspaceMasterStoreDataId/account/:masterDataAccountId/list`,
    pathname
  );
  const test1s = matchPath(
    `:workspaceMasterStoreDataId/account/:masterDataAccountId/list`,
    pathname
  );
  const testss = matchPath(
    {path: `:workspaceMasterStoreDataId?/account/:masterDataAccountId/list`},
    pathname
  );

but it never matches, am I doing something wrong ?

CodePudding user response:

The issue is the "?" in the path pattern. Try "/:workspaceMasterStoreDataId/account/:masterDataAccountId/list" as the path pattern.

const pattern = "/:workspaceMasterStoreDataId/account/:masterDataAccountId/list";
const pathname = "/1031/account/12/list";

const match = matchPath(pattern, pathname);

match Result:

{
  params: {
    workspaceMasterStoreDataId: '1031',
    masterDataAccountId: '12'
  },
  pathname: "/1031/account/12/list",
  pathnameBase: "/1031/account/12/list",
  pattern: {
    path: '/:workspaceMasterStoreDataId/account/:masterDataAccountId/list', 
    caseSensitive: false,
    end: true
  }
}

Seems odd that optional route path parameters are acceptable for the Route component's path prop, but doesn't work here. I see it listed as a feature request in the RRD github repo and in open discussion ATM.

CodePudding user response:

This looks like you are not using the API right. Its like this:

const match = matchPath(":workspaceMasterStoreDataId?/account/:masterDataAccountId/list", {
  path: pathname,
});
  • Related