react-router icon indicating copy to clipboard operation
react-router copied to clipboard

[Feature]: Enable link to same path match but with modified param value

Open Nate-Wessel opened this issue 4 years ago • 0 comments

What is the new or updated feature that you are suggesting?

I have a set of paths with a parameter like

  • /foo/:id
  • /foo/:id/bar
  • /foo/:id/baz/etc
  • ... each of which renders a component that I want to be able to link to the same path pattern, just with a different :id parameter. I don't want to have to worry about what comes before or after :id; I just want to link to whatever the current path is but with a given param altered.

Following an answer here I was able to come up with the following wrapper component that can pass the function I need, but you will notice that this just uses a simple replace function, not the actual match pattern, so it could easily mess things up if the param value occured anywhere else in the string.

function HOC(props){
	const { pathname } = useLocation()
	const { id } = useParams()
	const modPath = (new_id)=> pathname.replace(id,new_id);
	return <WrappedComponent {...{...props,modPath}}/>
}

In v5, I was able to do this by using withRouter which returned the actual match pattern, and a replace on the actual param identifier like this.props.match.path.replace(/:id/,new_id). I don't see an equally robust way of solving this problem in v6 though.

Why should this feature be included?

This seems like it would be a pretty common use case, and I haven't been able to solve it to my satisfaction in v6. The discussion on StackOverflow indicates that others are struggling with the same issue, again with no real solution.

Nate-Wessel avatar Feb 10 '22 18:02 Nate-Wessel