Maicmi
Maicmi

Reputation: 1104

ReactJS - How can I implement pagination for react with keep state when route change?

I have a react app, I use react-router v.4 and I use pagination from Jason. http://jasonwatmore.com/post/2017/03/14/react-pagination-example-with-logic-like-google

Everything is working fine but, when I change the route and then change the route back, the pagination changes the current page back to page 1.

How can I keep the page state when route change?

Upvotes: 8

Views: 10334

Answers (1)

Austin Coose
Austin Coose

Reputation: 256

With react router, there are multiple ways to handle this: The props from the Router pass down to you component, you can use a param:

<Route path="/items/:page" component={Component} />

and /items/1, /items/2 and use

props.match.params.page

Based on a quick view at the example, here:

this.setPage(this.props.match.params.page || this.props.initialPage)

And to change the url, in the onChangePage or even in the onClick handler, use something like this.props.history.push(`/items/${page}` . You could also use the location.pathname prop and parse the string, or use item?page=1 and parse location.search, etc.

If you want to maintain state globally and not from the router, you could use Redux.

Upvotes: 14

Related Questions