3

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.

asked Feb 13, 2022 at 11:51

1 Answer 1

9

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,
);
Diggy.
6,9543 gold badges23 silver badges39 bronze badges
answered Feb 13, 2022 at 13:00
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.