Change one of params in url with react-router v4

Viewed 3282

I have a path like this

/cities/:cityGuid/responses/:responseGuid

When a user changes a city, I need to replace :cityGuid. For changing city used a NavLink component.

<NavLink to="current url with changed cityGuid" text="Moscow" />

For getting a current url I need to use location.pathname and replace a cityGuid in this string.

current url: /cities/londonCityGuid/responses/abc1
user change city
next url is: /cities/moscowCityGuid/responses/abc1

What is the best way to do this?

2 Answers

If you want to keep the full location and change some parameters if you are in a nested route, you can do it with pathToRegexp, url and path from match and pathname from location.

const ParamLink = ({
  children,
  match: { url = '', path = '', params: currentParams = {} } = {},
  location: { pathname = '' } = {},
  params = {}
}) => {
  const urlPartToInsert = pathToRegexp.compile(path)({
    ...currentParams,
    ...params
  });
  const to = pathname.replace(url, urlPartToInsert);
  return <Link to={to}>{children}</Link>;
};

export default ParamLink;
import pathToRegexp from 'path-to-regexp';

const { match: { path, params } } = this.props;

pathToRegexp.compile(path)({
  ...params,
  cityGuid: 'newCityGuid',
})
Related