What is React-Paginate ? Differentiation of Styling the paging elements in ReactJS

if you are interested to learn about the React carousel

The Reactjs pagination library will be used directly for the pagination functionality of any list of items. The props required here are an array of list items to render and an on Change callback function, which informs the parent component about the page change. But pagination is important by filtering and displaying only relevant data, for example, Google search engine. Therefore, Reactjs pagination becomes crucial when users search for certain information and do not consume random information.

Some built-in libraries are used to handle pagination in web development, in the case of React. You directly use many resources to handle pagination in the application. Some of the NPM and other pagination libraries available are:

React-Paginate
  • react-js-paginate
  • react-paginate
  • react-boot/paginate

Instead of rewriting your own, it’s ideal to use these existing libraries, as there’s no need to reinvent the wheel; instead, you can focus on other things. But at the same time, it is very important to know what is going on behind the scenes to build and customize the app to your needs without compromising any requirements.

There is also a possibility that different logic is used for different reactjs pagination packages. To implement react pagination in your app, read this excellent react-jw-pagination article.

Here we talk only about react-paginate (the second one):

React-Paginate

A ReactJS component to render the pagination.

By installing the component and writing just a bit of CSS, you can get this: Note: You must write your CSS to get this UI. This package does not provide any CSS.

React-Paginate

or

React-Paginate

Installation

Install the react page with npm:  
npm install react-page --save  
import React, { useEffect, useState } from 'react';  
import ReactDOM from 'react-dom';  
import ReactPaginate from 'react-paginate';  
// Example to simulate obtaining the resources.  
constant elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];  
  
Function elements ({current elements}) {  
      return (  
        <>  
          {current items &&  
            currentelements.map((element) => (            <div>  
              <h3>Article #{article}</h3>  
            </div>  
          ))}  
      </>  
    );  
}function Paginated Items ({ items per page }) {  
  // We start with an empty list of elements.  
  const [currentitems, setcurrentitems] = useState(null);  
    const [pageCount, setPageCount] = useState(0);  
    // element offsets; we also use as page scrolls  
    // API we are working with.  
    const [element offset, set Element Offset] = usestate(0);  
  
    useEffect(() => {    // Get the items of other resources.  
    const endOffset = itemOffset + itemsPerPage;  
    console.log(`Loading items from ${itemOffset} to ${endOffset}`);  
    setCurrentItems(items.slice(itemOffset, endOffset));  
    setPageCount(Math.ceil(items.length / itemsPerPage));  
  }, [element offset, elements per page]);  
  
  // Call user clicks to request another page.  
  const handlePageClick = (event) => {  
    const newOffset = (event.selected * itemsPerPage) % items.length;  
    console.log(  
      `User requested page number ${event.selected}, offset by ${newOffset}`  
    );  
    setItemOffset(newOffset);  
  };  
  return (  
    <>  
      <articles current articles={current articles} />  
      <ReactPaginate  
        breakLabel="..."  
        nextLabel="next >"  
        onPageChange={handlePageClick}  
        Displayed Page Range = {5}  
        pageCount={pageCount}  
        previousLabel="< previous"  
        renderOnZeroPageCount={null}  
      />  
    </>  
  );  
}  
// Add a <div id="container"> to HTML to see the component.  
ReactDOM.render(  
  <Items Paginated itemsPerPage={4} />,  
  document.getElementById('container')  
);  

Try it on Code Pen.

You can read the code in demo/js/demo.js to understand make reactive pagination work in a list of objects. Finally, the CodePen demo introduces getting the sample code (GitHub API) and two synchronized widgets of pagination.

Props

NameTypeDescription
pageCountNumberThe total number of pages which is required.
PageRank displayedNumberThe range of pages which is displayed.
marginPagesDisplayedNumberThe number of pages has displayed in the margins.
previousLabelNodeIt is mainly used for Label for the previous button.
nextLabelNodeIt is used for Label for the next button.
breakLabelNodeMainly used for Label for ellipses.
breakClassNameStringThe name of the class in the li tag of the ellipsis element.
breakLinkClassNameStringThe name of the class is in the tag of the ellipsis element.
onPageChangeFunctionIt is used to call when a page is changed and exposes the page object as an argument.
onClickFunctionA callback for click on the component. Exposes information about the clicked (for example, is next for the next control), the expected next page, nextSelectedPage, and others. It returns prevents page changes or numbers from overriding the page again.
onPageActiveFunctionIt is used to call if any active page is clicked. It exposes the active page object as the argument.
initialPageNumberThe initial page is selected at uncontrolled mode. Don’t use it forcePage.
forcePageNumberTo override the selected page with the main prop. If you want to control the page from app state then use it.
disableInitialCallbackbooleanIt disable the onPageChange callback with the initial page. Default: false
containerClassNameStringIt is the class name of paging container.
classNameStringIt is same as the containerClassName. It is use with styled-components and other CSS-in-JS.
pageClassNameStringThe class name in the li tag of every page element.
pageLinkClassNameStringThe name of the class is the tag of each element on the page.
pageLabelBuilderFunctionIt is a function used to set the text links on the page. Default to (page) = page
activeClassNameStringThe name of the class for the active page.
activeLinkClassNameStringThe name of the class in the tag activates a.
previousClassNameStringThe name of the class is in the li tag of the previous button.
nextClassNameStringThe class name is in the li tag of the following button.
previousLinkClassNameStringThe name of the class is in a tag on the previous button.
nextLinkClassNameStringThe name of the class is on the tag of the next button.
disabledClassNameStringIt is used as the disabled previous and next buttons.
disabledLinkClassNameStringThe class name in the tag is used for disabled previous or next buttons.
hrefBuilderFunctionThe method is used to generate the attribute value in the tag of the element on the page.
hrefAllControlsBoolhrefBuilder adds hrefs as active controls by default. Set its property to true so that the hrefs will generate on all the controls.
extraAriaContextStringAdditional context to add the aria-label at the HTML attribute.
ariaLabelBuilderFunctionIt is called to generate the value of the aria-label attribute.
eventListenerStringThe event is used to listen to before changing the selected page. The default value is onClick here.
renderOnZeroPageCountFunctionA rendering function is called when pageCount is zero. Let the Next buttons shown by default. It does not display anything when a null value is supplied.
prevRelStringThe actual property in the tag is the control of the previous page. Default value prev. set is the null to disable.
nextRelStringThe actual property for the next page control. Next default value.
prevPageRelStringThe actual property in the tag is before the selected page. Default value prev. Set to null to disable.
selectedPageRelStringThe actual property in the selected page tag. Canonical default value. Set is null to disable.
nextPageRelStringThe actual property in the tag is right after the selected page-the next default value. Set is null to disable.

Demo

Clone the repository and access it easily to run the demo:

git clone git@github.com:AdeleD/react-paginate.git  
cd react-page  

Install the dependencies:

install npm  

Prepare the demo:

npm run demo  

Run the server:

npm run serve  

Open the browser and go to http://localhost:3000/.

React-Paginate

Here we implement a pagination element in React app by using the react-paginate.

Let’s start

Add and install react-paginate on a dependency in the app.

$ npm install react-page --save  

State Definition

current Page is index of the page selected by user, you may want to set it to 0, ie. the first page. Data contains all data elements. It is empty and we fill it after we get the data.

const [CurrentPage, setCurrentPage] = useState(0);  
const [data, setData] = useState([]);  
Getting the data  
useEffect(() => {  
    get information();  
  }, []); function fetchdata() {  
    search("https://ihsavru.me/Demo/uploads.json")  
      .then((res) => res.json())  
      .then((data) => {  
        constant {  
          course: {loads}  
        } = data;  
        setData(loads);  
      });  
  }  

Here, we create a useEffect hook by an empty dependency array that functions as the DidMount component’s lifecycle method and is responsible for getting the data and updating the data state. Calculation of data to represent the current page.

Let’s first define some constants:

const PER_PAGE = 10; const offset = current page * BY_PAGE; const current page data = data  
    .slice(offset, offset + BY_PAGE)  
    .map(({ thumburl }) => <img src={thumburl} />);const pageCount = Math.ceil(data.length / PER_PAGE);  

The PER_PAGE constant contains the number of items to display on each page, and an offset is the number of items that is already been displayed on previous pages.

If the current page is two (or the third page indexing starts by 0), then the offset becomes 20. It means that the first 20 elements have been rendered, and we will start rendering the next elements after 20 (the first page yielded the first ten items, 2nd the page yielded the next 10). The third page will render items 20 to 20 + BY_PAGE, 30.

This offset is used to set the current page elements, ie the current page data, which is mapped to an array of images using the split data.

let’s render the component:

return (  
    <div className="Application">  
      <h1>React pagination example</h1>  
      <ReactPaginate  
        previousLabel={"? Previous"}  
        nextLabel={"Next ?"}  
        pageCount={pageCount}  
        onPageChange={handlePageClick}  
        containerClassName={"paging"}  
        previouslinkClassName={"paging__link"}  
        nextLinkClassName={"paging__link"}  
        disabledClassName={"paging__link--disabled"}  
        activeClassName={"paging__link--active"}  
      />  
      {current page data}  
    </div>  
  );  

You can refer to this to see the different types of props passed to React paginate. When a new page is clicked here, a handle Page Click event handler function sets the current page.

function handlePageClick ({selected: selectedpage}) {  
      setCurrentPage(selectedpage);  
}  

Styling the pagination element

React-Paginate

It would be best to classify props like next Link Class Name, previous Link Class Name, disabled Class Name, and active Class Name to add classes of the pagination links for custom styling of the page.

What is React-Paginate ? Differentiation of Styling the paging elements in ReactJS
Show Buttons
Hide Buttons