import React, { Component, PropTypes } from "react"; import { Link, withRouter } from "react-router"; export class Pagination extends Component { constructor(props) { super(props); this.buildLinkTo.bind(this); } computePaginationBounds(currentPage, nPages, maxNumberPagesShown=5) { // Taken from http://stackoverflow.com/a/8608998/2626416 var lowerLimit = currentPage; var upperLimit = currentPage; for (var b = 1; b < maxNumberPagesShown && b < nPages;) { if (lowerLimit > 1 ) { lowerLimit--; b++; } if (b < maxNumberPagesShown && upperLimit < nPages) { upperLimit++; b++; } } return { lowerLimit: lowerLimit, upperLimit: upperLimit + 1 // +1 to ease iteration in for with < }; } buildLinkTo(pageNumber) { return { pathname: this.props.location.pathname, query: Object.assign({}, this.props.location.query, { page: pageNumber }) }; } goToPage() { const pageNumber = parseInt(this.refs.pageInput.value); $(this.refs.paginationModal).modal("hide"); if (pageNumber) { this.props.router.push(this.buildLinkTo(pageNumber)); } } dotsOnClick() { $(this.refs.paginationModal).modal(); } dotsOnKeyDown(ev) { ev.preventDefault; const code = ev.keyCode || ev.which; if (code == 13 || code == 32) { // Enter or Space key this.dotsOnClick(); // Fire same event as onClick } } cancelModalBox() { $(this.refs.paginationModal).modal("hide"); } render () { const { lowerLimit, upperLimit } = this.computePaginationBounds(this.props.currentPage, this.props.nPages); var pagesButton = []; var key = 0; // key increment to ensure correct ordering if (lowerLimit > 1) { // Push first page pagesButton.push(
  • Go to page 1
  • ); key++; if (lowerLimit > 2) { // Eventually push "…" pagesButton.push(
  • ); key++; } } var i = 0; for (i = lowerLimit; i < upperLimit; i++) { var className = "page-item"; var currentSpan = null; if (this.props.currentPage == i) { className += " active"; currentSpan = (current); } const title = "Go to page " + i; pagesButton.push(
  • Go to page {i} {currentSpan}
  • ); key++; } if (i < this.props.nPages) { if (i < this.props.nPages - 1) { // Eventually push "…" pagesButton.push(
  • ); key++; } const title = "Go to page " + this.props.nPages; // Push last page pagesButton.push(
  • Go to page {this.props.nPages}
  • ); } if (pagesButton.length > 1) { return (

    Page to go to?

    ); } return null; } } Pagination.propTypes = { currentPage: PropTypes.number.isRequired, location: PropTypes.object.isRequired, nPages: PropTypes.number.isRequired }; export default withRouter(Pagination);