Dark Mode

Pagination in React Javascript

March 18, 2021

Pagination is one of the most common component in the web apps and also in mobile apps. Lots of ecommerce website and content websites uses the pagination. The pagination helps to browse the content or datas of the apps. So lets create this pagination in REACT javascript today.

We will use the create react app for this tutorial. Lets start by generating a create react app boilerplate.

npx create-react-app Pagination

Now open the folder in your favourite code editor. We will work inside the src folder. First remove all the pre exisitng code inside of the App.js file.

To begin we need the data. For this I will create some array of data containing fruits name.

const datas = [
  "apple",
  "banana",
  "cherry",
  "guava",
  "mango",
  "orange",
  "peach",
  "raspberry",
  "kiwi",
  "watermelon",
  "grapes",
  "pomogranate",
  "avocado"
];

const firstIndex = 0;

Also we will use one constant variable to declare a firstindex. We will also need other varaibles but we will use them as state for the app. We will use the React hook useState for them.

States

const [pageSize, setPageSize] = React.useState(3);
const [page, setPage] = React.useState(1);
const [data, setData] = React.useState(datas.slice(firstIndex, pageSize));

Please dont forget to import the useState() hook from the react.

In the above useState we have declared three states. The pageSize is initialized to 3 which means every page will contain only 3 datas.

The page state keeps track of the page number. And finally the data state is for our data to be displayed in the page.

Lets create our sub component which will render a page number buttons. Lets name it Pagination.jsx.

Sub Component Pagination

import React from "react";

const Pagination = ({ count, handleChange }) => {
  let pages = [];
  for (let i = 1; i <= count; i++) {
    pages.push(
      <button
        value={i}
        key={i}
        className="btn btn-secondary"
        onClick={handleChange}
      >
        {i}
      </button>
    );
  }
  return (
    <>
      <div className="flex">{pages}</div>
    </>
  );
};

export default Pagination;

The sub component pagination has destructured props count and handleChange which will be comming from the parent component. Here we have used the for loop to use the count and create the number of buttons as to match the number of count. Later we retuned it rendering.

<div className="container">
      <ul className="lister">
        {data.map((d, i) => (
          <li key={i} className="lists">
            {d}
          </li>
        ))}
      </ul>
      <div className="pagenum">
        <label>Page: {page}</label>
      </div>
      <Pagination
        count={Math.ceil(datas.length / pageSize)}
        handleChange={handleChange}
      />
      <div className="form-group mt-2">
        <label className="form-label">Items per Page</label>
        <input
          className="form-control"
          type="number"
          onChange={changeWidth}
          value={pageSize}
        />
      </div>
    </div>

The above is the parent component return code. There we have called the Pagination component passing the count value and the handleChange function. Count is calculate by dividing the total number of data length by the pageSize. Also we used the Match.ceil function to pass the ceiling value.

React.useEffect(() => {
    setData(datas.slice(0, pageSize));
  }, [pageSize]);

  const handleChange = (e) => {
    let value = parseInt(e.target.value, 10);
    setPage(value);
    setData(datas.slice(firstIndex + pageSize * (value - 1), pageSize * value));
  };

  const changeWidth = (e) => {
    setPageSize(parseInt(e.target.value, 10));
  };

Now the above are the function codes that give functionality to the pagination. the useEffect() hook is used to initialize the data slice at the begining.

The handleChange function will slice the data as per the button value so that data will change as per the page.

And the changWidth function will allow to change the number of data visible in one page.

Sonahang Rai

About

In here I will write blogs about the react related stuffs. I will write tutorials mainly in here.

© 2021