I'm getting
pathname.match is not a function
error when I use matchPath of react-router
.
Here is the code that throws the exception:
import { matchPath, useLocation } from "react-router";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
const MatcherControl = () => {
const location = useLocation();
const match = matchPath(location.pathname, {
path: "/users/:id",
exact: true,
strict: false
});
return <div>{match ? "matches" : "not matches"}</div>;
};
This is the minimal example sandbox to reproduce the error.
CodePudding user response:
You are using react-router
v6 that the order of matchPath
arguments is inverted in new version:
declare function matchPath<
ParamKey extends string = string
>(
pattern: PathPattern | string,
pathname: string
): PathMatch<ParamKey> | null;
interface PathMatch<ParamKey extends string = string> {
params: Params<ParamKey>;
pathname: string;
pattern: PathPattern;
}
interface PathPattern {
path: string;
caseSensitive?: boolean;
end?: boolean;
}
Check it here
You should pass the pattern
first , and then pathname
:
const match = matchPath(
{ path: "/users/:id" },
location.pathname,
);