All files / Paginate index.js

100% Statements 15/15
100% Branches 8/8
100% Functions 4/4
100% Lines 14/14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46    1x                   2x 2x 2x 2x 2x     4x 4x 4x 4x         2x 1x         6x 6x                      
import React from "react"
 
const Context = React.createContext({})
 
export default class extends React.Component {
    static Consumer = Context.Consumer
    static defaultProps = {
        pageSize: 4
    }
    state = {
        page: 0,
        goTo: pn => {
            const { pageSize, total } = this.props
            const { page } = this.state
            pn = Math.max(0, pn)
            pn = Math.min(pn, Math.floor((total - 1) / pageSize))
            if (page !== pn) this.setState({ page: pn })
        },
        slice: arr => {
            const { pageSize } = this.props
            const { page } = this.state
            const offset = page * pageSize
            return arr.slice(offset, offset + pageSize)
        }
    }
 
    componentDidUpdate(prevProps) {
        if (prevProps.total !== this.props.total || prevProps.pageSize !== this.props.pageSize) {
            this.state.goTo(this.state.page)
        }
    }
 
    render() {
        const { children } = this.props
        return (
            <Context.Provider value={this.state}>
                {typeof children === "function" ? (
                    <Context.Consumer>{children}</Context.Consumer>
                ) : (
                    children
                )}
            </Context.Provider>
        )
    }
}