'how to only change a specific query params in react
Suppose I have this url:
/app/search?spaceId=**621cd16015**&resource_type=room&capacity=3
and I want to update only the spaceId based on click, so the new URL will be:
/app/search?spaceId=**14235ad**&resource_type=room&capacity=3
I'm using the class component. I used the following code to change the spaceId. It works, but it also removes all the other parameters too.
this.props.history.push({
pathname: "/app/search",
search: `?spaceId=${event}`,
});
Solution 1:[1]
You can use URLSearchParams object
const searchParams = new URLSearchParams('spaceId=spaceOldValue&resource_type=room&capacity=3');
searchParams.set('spaceId', 'spaceNewValue');
this.props.history.replace({
pathname: '/app/search',
search: searchParams.toString()
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yuval.bl |
