Murari Kumar
Murari Kumar

Reputation: 89

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}`,
    });

Upvotes: 1

Views: 3328

Answers (1)

yuval.bl
yuval.bl

Reputation: 5074

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()
  });

Upvotes: 2

Related Questions