6

I want to be able to create a link to the same route I'm on, except for changes to some parameters.

In my website, I decided to have a URL structured like this: /list/:page(\d+)?/:filter?. Now, in my component I have access to match (using withRouter HOC). In my situation it contains

{
  isExact: true
  params: {page: "3", filter: "duckbitt"}
  path: "/listing/:page(\d+)?/:filter?"
  url: "/listing/3/duckbitt"
}

This is very good, as I have both params and the path. Now, this raises 2 questions:

  1. Is there a react-router builtin solution for such a situation?

  2. If not, is there a possible solution using path-to-regexp, or I should use naive search and replace?

1 Answer 1

10

Of course a solution shows up right after posting the question.

import pathToRegexp from 'path-to-regexp';
// (...)
const toPath = pathToRegexp.compile(match.path);
const newPath = toPath({ ...match.params, page: 666 });
console.log(newPath); // "/listing/666/duckbitt"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.