React-router: How can I preserve query parameters when changing route?

Created on 7 Oct 2015  Â·  6Comments  Â·  Source: ReactTraining/react-router

Most helpful comment

For v4, its slightly different, as it uses search instead:

<Link to={{ pathname: '/somewhere/else', search: this.props.location.search}}>Go</Link>

All 6 comments

In your route component:

class Home extends React.Component {
  render() {
    return <Link to="/somewhere/else" query={this.props.query}>go somewhere else</Link>
  }
}
Warning: Unknown prop `query` on <a> tag. Remove this prop from the element.

Is there an updated way?

@lpender props.to can accept an object; on it you can define pathname and query properties. More info here (for v3), for example:

~jsx
const locationDescriptor = {
pathname: '/somewhere/else',
query: this.props.location.query
}
// …

~

You could also inline it

~jsx

~

For v4, its slightly different, as it uses search instead:

<Link to={{ pathname: '/somewhere/else', search: this.props.location.search}}>Go</Link>

Is there a way to do this when using history.push, instead of Link?

I tried

history.push({
  pathname: '/app/measurements',
  search: location.search,
});

but it causes an issue when, just before that line, an action is dispatched that updates the query params.

This is because at the time of calling history.push, location.search is one thing (call it A) and if the query string is updated (let's say to B), by some action between when history.push is called and when its result occurs, then .push incorrectly sets the query string back to A.

So preferably, instead of "preserving" search by re-setting it to its current value (which as described, can be tough to actually know at the time of calling .push), a more robust option would be where .push doesn't overwrite search in the first place. Does that make sense?

@tscizzle

history.push('/app/measurements' + history.location.search)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

nicolashery picture nicolashery  Â·  3Comments

jzimmek picture jzimmek  Â·  3Comments

yormi picture yormi  Â·  3Comments

andrewpillar picture andrewpillar  Â·  3Comments

Waquo picture Waquo  Â·  3Comments