How to update query param in url in React?

You could use location.pathname instead of location.search but all the other query parameters will also be deleted.

So if you have other parameters that you need and you only want to change the page parameter, you can use the URLSearchParams javascript object which will make it easier to replace the current pagination.

So do as follows:

Create a new variable which contains the current url with all the params:

let currentUrlParams = new URLSearchParams(window.location.search);

Then change the page parameter to the value you need in that variable:

currentUrlParams.set('page', pageNumber);

Now push the current url with the new params using history.push:

this.props.history.push(window.location.pathname + "?" + currentUrlParams.toString());

So the full code will be:

let currentUrlParams = new URLSearchParams(window.location.search);
currentUrlParams.set('page', pageNumber);
this.props.history.push(window.location.pathname + "?" + currentUrlParams.toString());

I think you should use pathname instead of search:

this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)

Tags:

Reactjs