Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set params in React Router v4

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?

like image 982
dhulme Avatar asked Mar 07 '23 01:03

dhulme


2 Answers

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.

like image 200
Mario Eis Avatar answered Mar 31 '23 10:03

Mario Eis


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"})
});
like image 39
Liran Brimer Avatar answered Mar 31 '23 10:03

Liran Brimer