11

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}
/>

2 Answers 2

15

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

2 Comments

this is changing url from /search?searchTerm=a to /searchTerm=a&page=2
this.props.history.push({ pathname: '/search', search: ${currentUrl.toString()} })
3

I think you should use pathname instead of search:

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

3 Comments

It dosent work this changed my url from search?searchTerm=a to search&page=2
Oh, you have other parameters! Are you using react-router?
there are other paramters in url

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.