Home > Blockchain >  How to parse url params from a URL with respect to route match path
How to parse url params from a URL with respect to route match path

Time:01-25

How do I parse any given url string with respect to match.path?

For example if the current route I am on is:

<Route path="/some/path/:type" /> I'd simply use match.params.type to get the type of the current url. But what if I have some URL string, const url = "/some/path/foo", is there a way I can parse this with respect to match.path?

I'm using react-router@5.

CodePudding user response:

You can use the matchPath utility to manually match a path string to a specified path. It returns a match object if there's a match, or null otherwise.

Example:

import { matchPath } from 'react-router';

const url = "/some/path/foo";
const path = "/some/path/:type";

const match = matchPath(url, { path });

console.log(match?.params.type); // "foo"
  • Related