CraZyDroiD
CraZyDroiD

Reputation: 7115

Update query strings onChange - reactjs

I have a url with query strings which looks like this

http://localhost:3000/collection?page=1&limit=15&filter=%27%27&filterInitDate=2019/11/11&filterEndDate=2019/11/11

I want to update just the filterInitDate when i select a date from my date input. I know i can update the url simply by using this.props.history.push but how can i just change/update the filterInitDate when i change the date input

ideally something like this

history.push(`/collection?filterInitDate=${startDate}`)

Upvotes: 0

Views: 464

Answers (1)

Titus
Titus

Reputation: 22484

You can use the URL and URLSearchParams classes for that, here is an example:

const urlStr = 'http://localhost:3000/collection?page=1&limit=15&filter=%27%27&filterInitDate=2019/11/11&filterEndDate=2019/11/11';
const url = new URL(urlStr);
url.searchParams.set("filterInitDate", "2019/11/12");

console.log(url.toString());

And an example specific to react router will look like this:

const query = new URLSearchParams(history.location.search);
query.set("filterInitDate", startDate);
history.replace({
  search: query.toString()
});

Upvotes: 1

Related Questions