Reputation: 1640
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}
/>
Upvotes: 11
Views: 28896
Reputation: 1322
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());
Upvotes: 15
Reputation: 3725
I think you should use pathname
instead of search
:
this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)
Upvotes: 3