Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update query param in url in React?

Tags:

reactjs

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}
/>
like image 581
vidy Avatar asked Jan 14 '19 12:01

vidy


People also ask

Does React router change URL?

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.

What is URLSearchParams in React?

The URLSearchParams interface defines utility methods to work with the query string of a URL.


1 Answers

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());
like image 100
Atef Avatar answered Sep 22 '22 19:09

Atef