1+ import React from 'react' ;
2+ import Pagination from "react-bootstrap/Pagination" ;
3+ import Alert from "react-bootstrap/Alert" ;
4+
5+ export const ITEMS_PER_PAGE = 30 ;
6+
7+ export class Paginator extends React . Component {
8+
9+ constructor ( props ) {
10+ super ( props ) ;
11+ this . state = {
12+ activePage : Math . round ( this . props . offset / ITEMS_PER_PAGE ) + 1 ,
13+ numberOfPages : Math . round ( this . props . totalItems / ITEMS_PER_PAGE ) ,
14+ }
15+ }
16+
17+ handleSelectPage ( selectedPage ) {
18+ if ( selectedPage > 0 && selectedPage <= this . state . numberOfPages ) {
19+ this . setState ( { activePage : selectedPage , loading : true } )
20+
21+ this . props . requestItemsHandler ( ( selectedPage - 1 ) * ITEMS_PER_PAGE , ITEMS_PER_PAGE )
22+ }
23+ }
24+
25+ render ( ) {
26+ if ( ! this . props . totalItems ) {
27+ return < div > Paginator not initialized correctly.</ div >
28+ }
29+ let loadingMessage ;
30+ if ( this . props . loading ) {
31+ loadingMessage = < Alert style = { { margin : '0.0' } } variant = { "light" } className = { "h-10" } >
32+ Reloading...
33+ </ Alert >
34+ }
35+
36+ let leftEllipses ;
37+ if ( this . state . activePage > 5 ) {
38+ leftEllipses = < Pagination . Ellipsis /> ;
39+ }
40+ let rightEllipses ;
41+ if ( this . state . activePage < this . state . numberOfPages - 5 ) {
42+ rightEllipses = < Pagination . Ellipsis /> ;
43+ }
44+
45+ let items = [ ] ;
46+ let firstDisplayedPage = this . state . activePage > 5 ? this . state . activePage - 4 : 1 ;
47+ let lastDisplayedPage = this . state . activePage < this . state . numberOfPages - 5 ? this . state . activePage + 4 : this . state . numberOfPages ;
48+ for ( let pageNumber = firstDisplayedPage ; pageNumber <= lastDisplayedPage ; pageNumber ++ ) {
49+ items . push (
50+ < Pagination . Item key = { pageNumber } active = { pageNumber === this . state . activePage }
51+ onClick = { ( ) => this . handleSelectPage ( pageNumber ) } >
52+ { pageNumber }
53+ </ Pagination . Item > ,
54+ ) ;
55+ }
56+
57+ return < div >
58+
59+ < Pagination >
60+ < Pagination . First onClick = { ( ) => this . handleSelectPage ( 1 ) } />
61+ < Pagination . Prev onClick = { ( ) => this . handleSelectPage ( this . state . activePage - 1 ) } />
62+ { leftEllipses }
63+ { items }
64+ { rightEllipses }
65+ < Pagination . Next onClick = { ( ) => this . handleSelectPage ( this . state . activePage + 1 ) } />
66+ < Pagination . Last onClick = { ( ) => this . handleSelectPage ( this . state . numberOfPages ) } />
67+ { loadingMessage }
68+ </ Pagination >
69+ </ div > ;
70+ }
71+ }
0 commit comments