Skip to content

Instantly share code, notes, and snippets.

@justusbluemer
Created July 2, 2019 12:13
Show Gist options
  • Save justusbluemer/693437ec380a7324547abd069dbc59eb to your computer and use it in GitHub Desktop.
Save justusbluemer/693437ec380a7324547abd069dbc59eb to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import classNames from 'classnames'
import styles from './Pager.styl'
import queryBuilder from './queryBuilder'
const Page = ({ page, currentPage, onClick }) => {
const diff = Math.abs(page.number - currentPage)
const className = classNames({
[styles.current]: page.isCurrent,
[styles.neighbour]: diff === 1,
[styles.standard]: diff > 1,
})
return (
<a data-pagenumber={page.number} onClick={onClick} className={className}>
{page.number}
</a>
)
}
export class Pager extends Component {
handlePageClick = ev => {
const { pager, location, history } = this.props
const pageNumber = parseInt(ev.target.getAttribute('data-pagenumber'))
history.push(queryBuilder(pager.url, location.search, 'page=' + pageNumber))
}
render() {
const { pager } = this.props
const { numberOfPages, currentPage } = pager
return (
<div className={this.props.className}>
{pager.hasPrev && (
<a
data-pagenumber={currentPage - 1}
onClick={this.handlePageClick}
className={styles.arrow}
>
&lt;
</a>
)}
{currentPage > 3 && numberOfPages > 5 && (
<span
data-pagenumber="1"
onClick={this.handlePageClick}
className={styles.number}
>
1 ...
</span>
)}
{Array.isArray(pager.pages)
? pager.pages.map((page, idx) => (
<Page
key={idx}
page={page}
onClick={this.handlePageClick}
currentPage={currentPage}
/>
))
: null}
{numberOfPages > 3 && numberOfPages > currentPage + 2 && (
<span
data-pagenumber={numberOfPages}
onClick={this.handlePageClick}
className={styles.number}
>
... {numberOfPages}
</span>
)}
{pager.hasNext && (
<a
data-pagenumber={currentPage + 1}
onClick={this.handlePageClick}
className={styles.arrow}
>
&gt;
</a>
)}
</div>
)
}
}
export default withRouter(
connect(state => ({ pager: state.pues.pager }))(Pager)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment