I am trying to create pagination in my web application using react-js-pagination. Pagination is showing in webpage but i want to change page param inside url according to page number like &page=4
. I tried to use
this.props.history.push(`${window.location.search}&page=${pageNumber}`)
but this is appending &page=4
everytime i click on pagination link. I know this wrong way to update url. How can i update only page parameter according to pageNumber in url?
handlePageChange = (pageNumber) => {
this.setState({activePage: pageNumber});
this.props.history.push(`${window.location.search}&page=${pageNumber}`)
}
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={10}
totalItemsCount={100}
onChange={this.handlePageChange}
/>
Thanks to the tools provided by react-router-dom, we can render components based on the url path and change that url path from any component in our React app.
The URLSearchParams interface defines utility methods to work with the query string of a URL.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With