Create Pagination in ReactJS using Bootstrap

Total
0
Shares

In this article I am going to show you how to create pagination in ReactJS using React Bootstrap pagination component. We will create the functionality for page numbers, next, previous, first page, last page buttons.

Install React Bootstrap

If you have not already installed react bootstrap, you can do it now using this command –

npm install react-bootstrap bootstrap

Now, we need to import pagination component into our files. Suppose we create a generic pagination component, MyPagination which can be used at multiple places in our project. So, it will look like this –

import React from 'react'
import Pagination from 'react-bootstrap/Pagination'

export default function MyPagination(props){

}

You will also need to include bootstrap css in your project. React-bootstrap will create the UI but styling is dependent on bootstrap, so include css in your index.js file –

import "bootstrap/dist/css/bootstrap.min.css";

Learn more about how to use bootstrap in ReactJS.

Bootstrap Pagination UI Items

Let’s see what pagination UI items are available in library that we can use –

UI Type Bootstrap Code Description
First Page («) <Pagination.First /> Used to jump to the first page
Previous Page (‹) <Pagination.Prev /> Used to go back one page
Page Number (3) <Pagination.Item>{3}</Pagination.Item> To show different page numbers
Ellipsis (…) <Pagination.Ellipsis /> To show a large group of pages
Next Page (›) <Pagination.Next /> Used to go to next page
Last Page (») <Pagination.Last /> To jump to the last page

When we use these UI items together, they will render something like this –

<Pagination>
  <Pagination.First />
  <Pagination.Prev />
  <Pagination.Item>{1}</Pagination.Item>
  <Pagination.Ellipsis />

  <Pagination.Item>{10}</Pagination.Item>
  <Pagination.Item>{11}</Pagination.Item>
  <Pagination.Item active>{12}</Pagination.Item>
  <Pagination.Item>{13}</Pagination.Item>
  <Pagination.Item disabled>{14}</Pagination.Item>

  <Pagination.Ellipsis />
  <Pagination.Item>{20}</Pagination.Item>
  <Pagination.Next />
  <Pagination.Last />
</Pagination>

Want to learn about most common bootstrap components? Check out this guide – Top 10 Bootstrap components.

Pagination Logic

We will need to know few important values before moving forward –

  1. Total Pages – Total number of pages will be needed to create the range from 1 to total pages.
  2. Current Page – It decides what will be the previous and next page numbers.
  3. On Click Function – This function will be called when there is click on any pagination button.

We pass all these values through props into our MyPagination component. We are going to name them as –

  1. Total Pagesprops.totPages
  2. Current Pageprops.currentPage
  3. Function props.pageClicked(page_number)

Code – MyPagination.js

import React from "react";
import Pagination from "react-bootstrap/Pagination";

export default function MyPagination(props) {
  const [pageArray, setPageArray] = React.useState([]);

  React.useEffect(() => {
    var totPages = parseInt(props.totPages);
    var currentPage = parseInt(props.currentPage);
    var pageArr = [];
    if (totPages > 1) {
      if (totPages <= 9) {
        var i = 1;
        while (i <= totPages) {
          pageArr.push(i);
          i++;
        }
      } else {
        if (currentPage <= 5) pageArr = [1, 2, 3, 4, 5, 6, 7, 8, "", totPages];
        else if (totPages - currentPage <= 4)
          pageArr = [
            1,
            "",
            totPages - 7,
            totPages - 6,
            totPages - 5,
            totPages - 4,
            totPages - 3,
            totPages - 2,
            totPages - 1,
            totPages
          ];
        else
          pageArr = [
            1,
            "",
            currentPage - 3,
            currentPage - 2,
            currentPage - 1,
            currentPage,
            currentPage + 1,
            currentPage + 2,
            currentPage + 3,
            "",
            totPages
          ];
      }
    }
    setPageArray(pageArr);
  }, []);

  return (
    <React.Fragment>
      {props.children}
      <div style={{ marginTop: "15px" }}>
        <Pagination style={{ justifyContent: "center" }}>
          {pageArray.map((ele, ind) => {
            const toReturn = [];

            if (ind === 0) {
              toReturn.push(
                <Pagination.First
                  key={"firstpage"}
                  onClick={
                    props.currentPage === 1
                      ? () => {}
                      : () => {
                          props.pageClicked(1);
                        }
                  }
                />
              );

              toReturn.push(
                <Pagination.Prev
                  key={"prevpage"}
                  onClick={
                    props.currentPage === 1
                      ? () => {}
                      : () => {
                          props.pageClicked(props.currentPage - 1);
                        }
                  }
                />
              );
            }

            if (ele === "") toReturn.push(<Pagination.Ellipsis key={ind} />);
            else
              toReturn.push(
                <Pagination.Item
                  key={ind}
                  active={props.currentPage === ele ? true : false}
                  onClick={
                    props.currentPage === ele
                      ? () => {}
                      : () => {
                          props.pageClicked(ele);
                        }
                  }
                >
                  {ele}
                </Pagination.Item>
              );

            if (ind === pageArray.length - 1) {
              toReturn.push(
                <Pagination.Next
                  key={"nextpage"}
                  onClick={
                    props.currentPage === ele
                      ? () => {}
                      : () => {
                          props.pageClicked(props.currentPage + 1);
                        }
                  }
                />
              );

              toReturn.push(
                <Pagination.Last
                  key={"lastpage"}
                  onClick={
                    props.currentPage === ele
                      ? () => {}
                      : () => {
                          props.pageClicked(ele);
                        }
                  }
                />
              );
            }

            return toReturn;
          })}
        </Pagination>
      </div>
    </React.Fragment>
  );
}

You can use this component in your projects directly where you need to add pagination. To use it, first include it and then wrap the component –

import MyPagination from './MyPagination'

export default function listWherePaginationUsed(){
  return(
    <MyPagination totPages={25} currentPage={3} pageClicked={(ele) => {}}>
      <ul>
        <li>Item 21</li>
        <li>Item 22</li>
        ...
        <li>Item 30</li>
      </ul>
    </MyPagination>
  )
}

It will render a list of items from 21 to 30. The pagination bar will show page number 3 to be highlighted. Total pages in the bar will be 25. Although button clicks won’t do anything because our pageClicked function is empty. In this function you need to define page change logic which include API calls or changing list content locally.

Working Code Example

File – MyPagination.js

import React from "react";
import Pagination from "../node_modules/react-bootstrap/Pagination";

export default function MyPagination(props) {
  const [pageArray, setPageArray] = React.useState([]);

  React.useEffect(() => {
    var totPages = parseInt(props.totPages);
    var currentPage = parseInt(props.currentPage);
    var pageArr = [];
    if (totPages > 1) {
      if (totPages <= 9) {
        var i = 1;
        while (i <= totPages) {
          pageArr.push(i);
          i++;
        }
      } else {
        if (currentPage <= 5) pageArr = [1, 2, 3, 4, 5, 6, 7, 8, "", totPages];
        else if (totPages - currentPage <= 4)
          pageArr = [
            1,
            "",
            totPages - 7,
            totPages - 6,
            totPages - 5,
            totPages - 4,
            totPages - 3,
            totPages - 2,
            totPages - 1,
            totPages
          ];
        else
          pageArr = [
            1,
            "",
            currentPage - 3,
            currentPage - 2,
            currentPage - 1,
            currentPage,
            currentPage + 1,
            currentPage + 2,
            currentPage + 3,
            "",
            totPages
          ];
      }
    }
    setPageArray(pageArr);
  }, []);

  return (
    <React.Fragment>
      {props.children}
      <div style={{ marginTop: "15px" }}>
        <Pagination style={{ justifyContent: "center" }}>
          {pageArray.map((ele, ind) => {
            const toReturn = [];

            if (ind === 0) {
              toReturn.push(
                <Pagination.First
                  key={"firstpage"}
                  onClick={
                    props.currentPage === 1
                      ? () => {}
                      : () => {
                          props.pageClicked(1);
                        }
                  }
                />
              );

              toReturn.push(
                <Pagination.Prev
                  key={"prevpage"}
                  onClick={
                    props.currentPage === 1
                      ? () => {}
                      : () => {
                          props.pageClicked(props.currentPage - 1);
                        }
                  }
                />
              );
            }

            if (ele === "") toReturn.push(<Pagination.Ellipsis key={ind} />);
            else
              toReturn.push(
                <Pagination.Item
                  key={ind}
                  active={props.currentPage === ele ? true : false}
                  onClick={
                    props.currentPage === ele
                      ? () => {}
                      : () => {
                          props.pageClicked(ele);
                        }
                  }
                >
                  {ele}
                </Pagination.Item>
              );

            if (ind === pageArray.length - 1) {
              toReturn.push(
                <Pagination.Next
                  key={"nextpage"}
                  onClick={
                    props.currentPage === ele
                      ? () => {}
                      : () => {
                          props.pageClicked(props.currentPage + 1);
                        }
                  }
                />
              );

              toReturn.push(
                <Pagination.Last
                  key={"lastpage"}
                  onClick={
                    props.currentPage === ele
                      ? () => {}
                      : () => {
                          props.pageClicked(ele);
                        }
                  }
                />
              );
            }

            return toReturn;
          })}
        </Pagination>
      </div>
    </React.Fragment>
  );
}

File – index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import "bootstrap/dist/css/bootstrap.min.css";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);

File – App.js

import React from "react";
import MyPagination from "./MyPagination";

export default function App() {
  const [tagList, setTagList] = React.useState([]);
  const [currPage, setCurrPage] = React.useState(3);

  React.useEffect(() => {
    afterPageClicked(3);
  }, []);

  const afterPageClicked = (page_number) => {
    setCurrPage(page_number);
    fetch(`https://dummyapi.io/data/api/tag?limit=10&page=${page_number}`, {
      headers: {
        "app-id": "60983c4f56c487f12fd13e23"
      }
    })
      .then((response) => response.json())
      .then((data) => setTagList(data.data));
  };

  return (
    <MyPagination
      totPages={20}
      currentPage={currPage}
      pageClicked={(ele) => {
        afterPageClicked(ele);
      }}
    >
      <ul>
        {tagList.map((ele, ind) => {
          return <li key={ele + ind}>{ele}</li>;
        })}
      </ul>
    </MyPagination>
  );
}

    Tweet this to help others

Live Demo

Open Live Demo