DEV Community

Cover image for Create Pagination in React
Chetan Rohilla
Chetan Rohilla

Posted on • Edited on • Originally published at w3courses.org

9 1

Create Pagination in React

Pagination is the process of splitting the contents, or a section of contents from a website or application, into discrete pages.

Create Pagination in React

class Pagination extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      currentPage: null,
      pageCount: null
    }
  }

  componentWillMount() {
    const startingPage = this.props.startingPage
      ? this.props.startingPage
      : 1;
    const data = this.props.data;
    const pageSize = this.props.pageSize;
    let pageCount = parseInt(data.length / pageSize);
    if (data.length % pageSize > 0) {
      pageCount++;
    }
    this.setState({
      currentPage: startingPage,
      pageCount: pageCount
    });
  }

  setCurrentPage(num) {
    this.setState({currentPage: num});
  }

  createControls() {
    let controls = [];
    const pageCount = this.state.pageCount;
    for (let i = 1; i <= pageCount; i++) {
      const baseClassName = 'pagination-controls__button';
      const activeClassName = i === this.state.currentPage ? `${baseClassName}--active` : '';
      controls.push(
        <div
          className={`${baseClassName} ${activeClassName}`}
          onClick={() => this.setCurrentPage(i)}
        >
          {i}
        </div>
      );
    }
    return controls;
  }

  createPaginatedData() {
    const data = this.props.data;
    const pageSize = this.props.pageSize;
    const currentPage = this.state.currentPage;
    const upperLimit = currentPage * pageSize;
    const dataSlice = data.slice((upperLimit - pageSize), upperLimit);
    return dataSlice;
  }

  render() {
    return (
      <div className='pagination'>
        <div className='pagination-controls'>
          {this.createControls()}
        </div>
        <div className='pagination-results'>
          {React.cloneElement(this.props.children, {data: this.createPaginatedData()})}
        </div>
      </div>
    );
  }
}

Pagination.propTypes = {
  data: React.PropTypes.array.isRequired,
  pageSize: React.PropTypes.number.isRequired,
  startingPage: React.PropTypes.number.isRequired
};

Pagination.defaultProps = {
  pageSize: 4,
  startingPage: 1
};

class Content extends React.Component {

  render() {
    const data = this.props.data;
    return (
      <div className='content'>
        {data.map((item) => {
          return (
            <div className='content__item'>
              {item.id} {item.item_name}
            </div>
          );
        })}
      </div>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <Pagination
        data={sampleData()}
      >
        <Content />
      </Pagination>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

function sampleData() {
  return (
    [{"id":1,"item_name":"Item 1"},
    {"id":2,"item_name":"Item 2"},
    {"id":3,"item_name":"Item 3"},
    {"id":4,"item_name":"Item 4"},
    {"id":5,"item_name":"Item 5"},
    {"id":6,"item_name":"Item 6"},
    {"id":7,"item_name":"Item 7"},
    {"id":8,"item_name":"Item 8"},
    {"id":9,"item_name":"Item 9"},
    {"id":10,"item_name":"Item 10"}]
  );
}
Enter fullscreen mode Exit fullscreen mode

Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please visit my website.

Thanks:)
Happy Coding:)

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay