Handling Pagination Changes
When we click on each pagination, let’s make that pagination index active.
First, let’s put a callback for when the pagination happens.
movies.jsx
In the render function:
1 2 3 4 5 6 |
<Pagination itemsCount={count} pageSize={pageSize} currentPage={currentPage} onPageChange={this.handlePageChange} /> |
The handler itself:
1 2 3 4 5 6 |
handlePageChange = page => { console.log('you have clicked on page: ', page); this.setState({ currentPage: page }) } |
update our state:
1 2 3 4 5 |
state = { movies: getMovies(), pageSize: 4, currentPage: 1, } |
Whenever a pagination is clicked, it calls the movies component to update and set its state’s currentPage.
Hence, in our Pagination, we get the currentPage successfully. We do UI updates, so let’s put the class ‘active’ in our HTML whenever the currentPage matches our current displayed page.
When we loop through each pagination page number to be displayed, if that page number equals our currentPage, then we put the active class. Else, don’t put it. That way, we highlight the page that we’re on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
return <nav> <ul className="pagination"> {pagesArr.map(page => { let isActive = page === currentPage ? 'page-item active' : 'page-item'; return ( <li key={page} className={isActive}> <a className="page-link" onClick={() => onPageChange(page)}> {page} </a> </li> ) } )} </ul> </nav> |
You should now see the highlighted pagination