how to implement Pagination in reactJs

后端 未结 10 1523
抹茶落季
抹茶落季 2020-11-28 02:05

I am new to ReactJS and am creating a simple TODO application in it. Actually, it is a very basic app with no db connection, tasks are stored in an array. I added Edit and D

10条回答
  •  独厮守ぢ
    2020-11-28 02:56

    Here is a way to create your Custom Pagination Component from react-bootstrap lib and this component you can use Throughout your project

    Your Pagination Component (pagination.jsx or js)

    import React, { Component } from "react"; 
    import { Pagination } from "react-bootstrap"; 
    import PropTypes from "prop-types";
    
    export default class PaginationHandler extends Component {  
    
       constructor(props) {
        super(props);
        this.state = {
          paging: {
            offset: 0,
            limit: 10
          },
          active: 0
        };  
        }
    
      pagingHandler = () => {
        let offset = parseInt(event.target.id);
        this.setState({
          active: offset
        });
        this.props.pageHandler(event.target.id - 1);   };
    
      nextHandler = () => {
        let active = this.state.active;
        this.setState({
          active: active + 1
        });
        this.props.pageHandler(active + 1);   };
    
      backHandler = () => {
        let active = this.state.active;
        this.setState({
          active: active - 1
        });
        this.props.pageHandler(active - 1);   };
    
      renderPageNumbers = (pageNumbers, totalPages) => {
        let { active } = this.state;
        return (
          
            5 && this.backHandler} />
    
            {
          pageNumbers.map(number => {
                  if (
                    number >= parseInt(active) - 3 &&
                    number <= parseInt(active) + 3 
                  ) {
                    return (
                      
                        {number}
                      
                    );
                  } else {
                    return null;
                  }
            })}
            
          
        );   };
    
      buildComponent = (props, state) => {
        const { totalPages } = props;
        const pageNumbers = [];
        for (let i = 1; i <= totalPages; i++) {
          pageNumbers.push(i);
        }
        return (
          
    {this.renderPageNumbers(pageNumbers ,totalPages)}
    ); }; render() { return this.buildComponent(this.props, this.state); } } PaginationHandler.propTypes = { paging: PropTypes.object, pageHandler: PropTypes.func, totalPages: PropTypes.object };

    Use of Above Component in your Component

    import Pagination from "../pagination";
    
    pageHandler = (offset) =>{
          this.setState(({ paging }) => ({
            paging: { ...paging, offset: offset }
          }));
       }
       render() {
        return (
          
    ); }

提交回复
热议问题