In React Router 4 I can define
<Route path="/calendar/:view/:year?/:month?/:day?" component={Calendar} />
to pass props from a URL to my Calendar component.
Inside the Calendar component, I want to programmatically set the URL params. The docs show how to do this using history.push()
, but this requires you to format the URL yourself like history.push(``${view}/${year}/${month}/${day}``)
. But I want to update the URL without being coupled to the route structure, ideally something like history.push({ view: 'month', year: '2018' })
.
Is this possible? It seems odd to me that React Router helps split up the URL into params, but doesn't provide a nice mechanism to set those params?
I do that by using match.path and generatePath. Here is an example:
this.props.history.push({
pathname: generatePath(this.props.match.path, {orderId: "latest", orderItemId: "latest"})
});
You can read about it here https://reacttraining.com/react-router/core/api/generatePath and here https://reacttraining.com/react-router/core/api/match.
Thats the cleanest solution I found so far for preventing the route component from knowing to much about where it will be allocated later in the path structure. Maybe it fits your (or someone else's) need.
I would like to suggest that instead of history.push()
as answered, you would use history.replace()
.
with replace
you would not affect the history in case the user would want to navigate backward in the browser.
this.props.history.replace({
pathname: generatePath(this.props.match.path, {orderId: "latest", orderItemId: "latest"})
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With