Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m using react-router@5.

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading