Home Reference Source

application/components/common/redux-paginator.js

import React from 'react';

/**
 * ReduxPagination stateful component. This does not update the url
 * and instead relies on the internal redux state.
 * Use the onPaginate parameter to watch for changes.
 * Expects pagination property to be API standard.
 */
class ReduxPaginator extends React.Component {

    constructor(props) {
        super(props);

        this.onPaginate = this.onPaginate.bind(this);
    }

    onPaginate(...params) {
        if (this.props.onPaginate) {
            this.props.onPaginate(...params);
        }
    }

    render() {
        if (!this.props.pagination) {
            return (
                <ul className="pagination"></ul>
            );
        }

        let pages = [];
        let pagination = this.props.pagination;
        if (pagination.size) {
            pagination = pagination.toJS();
        }

        let previousClass = 'waves-effect';
        if (parseInt(pagination.before) === parseInt(pagination.current)) {
            previousClass = 'disabled';
        }
        let nextClass = '';
        if (parseInt(pagination.current) === parseInt(pagination.last)) {
            nextClass = 'disabled';
        }

        const previous = (
            <li className={previousClass} style={{cursor:'pointer'}}>
                <span onClick={this.onPaginate.bind(this, pagination.before)}><i className='fa fa-chevron-left'></i></span>
            </li>
        );
        const next = (
            <li className={nextClass} style={{cursor:'pointer'}}>
                <span onClick={this.onPaginate.bind(this, pagination.next)}><i className='fa fa-chevron-right'></i></span>
            </li>
        );

        const total = parseInt(pagination.total_pages);
        const current = parseInt(pagination.current);
        if (total <= 8) {
            for (let i = 0; i < total; i++) {
                pages.push((
                    <li key={(i+1)} className={((i+1) === current) ? 'active' : 'waves-effect'}>
                        <span onClick={this.onPaginate.bind(this, (i+1))} style={{cursor:'pointer'}}>{(i+1)}</span>
                    </li>
                ));
            }
        } else {
            let start = 1;
            if (current > 6) {
                start = current - 5;
            }
            let max = start+8;
            if (total <= 8) {
                max = total;
            }
            for (let i = start; i < max; i++) {
                pages.push((
                    <li key={i} className={(i === current) ? 'active' : 'waves-effect'}>
                        <span onClick={this.onPaginate.bind(this, i)} style={{'cursor':'pointer'}}>{i}</span>
                    </li>
                ));
            }
        }

        return (
            <ul className="pagination">
                {previous}
                {pages}
                {next}
            </ul>
        );

    }
}

export default ReduxPaginator;