1

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}`,
    });
4
  • Did you try replace? Maybe with a regular expression? There's also the URL API. Commented Mar 5, 2022 at 5:16
  • @Andy i cant replace as the spaceId is dynamic. How can I get old spaceId everytime to replace. Commented Mar 5, 2022 at 5:20
  • You can switch to functional component and use useQueryParams hook. Commented Mar 5, 2022 at 6:33
  • @MohitKushwaha I cant i m on client project Commented Mar 5, 2022 at 6:42

1 Answer 1

2

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()
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.