How to create pagination from array in react using class component

How to implement pagination on array in react using class component

Posted by Raquel Crist on January 15, 2022

Sometimes you have a large list that you need to paginate in order to view it in chunks. As data grow it becomes more and more essential to display paginated. 

So, let's get started!

Step 1. Create react application

Run command below:

npx create-react-app react-pagination

If you need some guidance on how to create react app, go to https://wecode101.com/create-react-app.

Step 2. Install dependencies

run command below from root of project:

npm install mdbreact react-paginate bootstrap font-awesome

Step 3. Edit /src/App.js

Add dependencies:
import "bootstrap/dist/css/bootstrap.min.css";
import {MDBCard, MDBCardHeader, MDBCardTitle, MDBCardBody, MDBCardText} from "mdbreact";
import ReactPaginate from 'react-paginate';
Convert function to class:
class App extends Component {
    constructor(props) {
        super(props);
    }
    
     render() {
          return (
       <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
    }
}
export default App;
Add states to constructor:
this.state = {
  perPage: 3,
  page: 0,
  pages: 0
};
Add array below constructor:

This array has been shortened just to improve readability. You will have to add more items or download the project to see the pagination effect.

 items =[
       {
        job:"teacher",
        location:"London",
        salary:"£25k",
        jobType:"permanent",
        description:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        postedBy:"Jack Rock"
       },
        {
            job:"mechanic",
            location:"Birmingham",
            salary:"£22k",
            jobType:"permanent",
            description:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            postedBy:"Jack Rock"
        }
];
Add component method:

This will determine the quantity of items per page.

componentDidMount() {
  this.setState({
     pages: Math.floor(this.jobs.length / this.state.perPage)
  });
}
Add click method:

This will allow you to see the items on the specific pagination number onclick.

handlePageClick = (event) => {
  let page = event.selected;
  this.setState({page})
}
Add to top of render method:

The logic for the items variable will break the jobs list down into segments of arrays in order to provide the right number of items for each page.

const {page, perPage, pages} = this.state;
let items = this.jobs.slice(page * perPage, (page + 1) * perPage);

Replace code in render method:

return (
           <div className="container">
              <div className="mx-auto col-7">
                  <div className="mt-5 mb-5"><h1>All Jobs</h1></div>
                  {this.items.map((value, i) => {
                      return (
                          <MDBCard key={i} className="op-widget-pd mb-4">
                              <MDBCardHeader className="tt-bg">
                                  <div className="row">
                                      <div className="col-10">
                                          <MDBCardTitle id="jb-rlt">{value.job}</MDBCardTitle>
                                      </div>
                                      <div
                                          className="col-1 offset-1 badge clr-gry-bg rounded-pill text-dark text-center txt-pd">New
                                      </div>
                                  </div>
                              </MDBCardHeader>
                              <MDBCardBody>
                                  <div className="row text-start">
                                      <MDBCardText className="col-4 pt-txt"><i
                                          className="fa fa-map-marker-alt main-theme-color"/><i className="fa fa-map-marker"/> {value.location}</MDBCardText>
                                      <MDBCardText className="col-4 pt-txt"><i
                                          className="fa fa-pound-sign main-theme-color"/> {value.salary}</MDBCardText>
                                      <MDBCardText className="col-4 pt-txt"><i
                                          className="fa fa-clock main-theme-color"/> {value.jobType}</MDBCardText>
                                  </div>
                                  <MDBCardText className="text-start">{value.description}</MDBCardText>
                                  <div className="trm-txt pt-3 pb-3">Posted 6 days ago by <a className="main-theme-color"
                                                                                             href="#">{value.postedBy}</a>
                                  </div>
                                  <div className="main-theme-color">Read more <i className="fa fa-arrow-circle-right"/>
                                  </div>
                              </MDBCardBody>
                          </MDBCard>
                      )
                  })
                  }
                  <div className="pagination-txt">Display {this.state.perPage} of {this.items.length} relevant
                      jobs
                  </div>
                  <div className="float-end">
                      <ReactPaginate
                          previousLabel={'<<'}
                          nextLabel={'>>'}
                          pageCount={5}
                          onPageChange={this.handlePageClick}
                          containerClassName={'pagination'}
                          activeClassName={'active'}
                      />
                  </div>
              </div>
          </div>
          );

Step 4. Add css for pagination styling

Go to /src directory and create pagination.css and add code below:
.pagination {
    display: flex;
    list-style: none;
    padding: 0;
    font-size:12px;
}

.pagination a {
    cursor: default;
    padding: 7px;
    border-radius: 6px;
    border: 1px solid purple;
    color: purple;
    margin-left: 10px;
}

.pagination li:not(.disabled) a:hover {
    cursor: pointer;
}

.pagination li a {
    font-weight: bold;
    text-decoration: none;
}

.pagination li.active a {
    color: purple;
}

.pagination li.disabled a {
    pointer-events: none;
    color: rgb(198, 197, 202);
    border: 1px solid rgb(198, 197, 202);
}

.pagination-txt{
    display: inline;
    font-size: 12px;
}

Step 5. Execute command

npm run start

You should see pagination in action once you go to the link http://localhost:3000.

Finally, here is what App.js looks like all together:
import React, { Component } from "react";
import './App.css';
import './paginate.css';
import "bootstrap/dist/css/bootstrap.min.css";
import {MDBCard, MDBCardHeader, MDBCardTitle, MDBCardBody, MDBCardText} from "mdbreact";
import ReactPaginate from 'react-paginate';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            perPage: 3,
            page: 0,
            pages: 0
        };
    }

    jobs =[
       {
        job:"Teacher",
        location:"London",
        salary:"£25k",
        jobType:"permanent",
        description:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        postedBy:"Jack Rock"
       },
       {
            job:"Mechanic",
            location:"Birmingham",
            salary:"£22k",
            jobType:"permanent",
            description:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            postedBy:"Jack Rock"
        }
    ];

    componentDidMount() {
        this.setState({
            pages: Math.floor(this.jobs.length / this.state.perPage)
        });
    }

    handlePageClick = (event) => {
        let page = event.selected;
        this.setState({page})
    }

   render() {
      const {page, perPage, pages} = this.state;
      let items = this.jobs.slice(page * perPage, (page + 1) * perPage);

      return (
          <div className="container">
              <div className="mx-auto col-7">
                  <div className="mt-5 mb-5"><h1>All Jobs</h1></div>
                  {items.map((value, i) => {
                      return (
                          <MDBCard key={i} className="op-widget-pd mb-4">
                              <MDBCardHeader className="tt-bg">
                                  <div className="row">
                                      <div className="col-10">
                                          <MDBCardTitle id="jb-rlt">{value.job}</MDBCardTitle>
                                      </div>
                                      <div
                                          className="col-1 offset-1 badge clr-gry-bg rounded-pill text-dark text-center txt-pd">New
                                      </div>
                                  </div>
                              </MDBCardHeader>
                              <MDBCardBody>
                                  <div className="row text-start">
                                      <MDBCardText className="col-4 pt-txt"><i
                                          className="fa fa-map-marker-alt main-theme-color"/><i className="fa fa-map-marker"/> {value.location}</MDBCardText>
                                      <MDBCardText className="col-4 pt-txt"><i
                                          className="fa fa-pound-sign main-theme-color"/> {value.salary}</MDBCardText>
                                      <MDBCardText className="col-4 pt-txt"><i
                                          className="fa fa-clock main-theme-color"/> {value.jobType}</MDBCardText>
                                  </div>
                                  <MDBCardText className="text-start">{value.description}</MDBCardText>
                                  <div className="trm-txt pt-3 pb-3">Posted 6 days ago by <a className="main-theme-color"
                                                                                             href="#">{value.postedBy}</a>
                                  </div>
                                  <div className="main-theme-color">Read more <i className="fa fa-arrow-circle-right"/>
                                  </div>
                              </MDBCardBody>
                          </MDBCard>
                      )
                  })
                  }
                  <div className="pagination-txt">Display {this.state.perPage} of {this.jobs.length} relevant
                      jobs
                  </div>
                  <div className="float-end">
                      <ReactPaginate
                          previousLabel={'<<'}
                          nextLabel={'>>'}
                          pageCount={pages}
                          onPageChange={this.handlePageClick}
                          containerClassName={'pagination'}
                          activeClassName={'active'}
                      />
                  </div>
              </div>
          </div>
      );
  }
}

export default App;
Enjoy!

Download project here

Please execute npm install within project root, if you plan to download the project above.