Cover Image for React-Paginate
301 views

React-Paginate

The react-paginate is a popular pagination library for React applications that provides an easy way to add pagination to lists, tables, or any type of data that requires navigation through pages. It offers various features for creating pagination controls and handling page changes in a user-friendly manner.

Here’s how you can use the react-paginate library in a React application:

  1. Install the react-paginate library:
Bash
npm install react-paginate
  1. Create a PaginatedList Component:

Create a component that renders your paginated list along with the pagination controls provided by react-paginate. Here’s a basic example:

TypeScript
import React, { useState } from 'react';
import ReactPaginate from 'react-paginate';
import './App.css'; // Add your CSS file for styling

function PaginatedList() {
  const itemsPerPage = 5; // Number of items to display per page
  const items = Array.from({ length: 20 }, (_, index) => `Item ${index + 1}`);
  const [currentPage, setCurrentPage] = useState(0);

  const handlePageClick = (selectedPage) => {
    setCurrentPage(selectedPage.selected);
  };

  const startIndex = currentPage * itemsPerPage;
  const displayedItems = items.slice(startIndex, startIndex + itemsPerPage);

  return (
    <div>
      <h1>Paginated List</h1>
      <ul>
        {displayedItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <ReactPaginate
        pageCount={Math.ceil(items.length / itemsPerPage)}
        pageRangeDisplayed={2}
        marginPagesDisplayed={1}
        onPageChange={handlePageClick}
        containerClassName="pagination"
        activeClassName="active"
      />
    </div>
  );
}

export default PaginatedList;
  1. Styling:

You can style the pagination controls using CSS. In the example above, we used containerClassName and activeClassName props to add classes for styling purposes.

  1. Use the PaginatedList Component:

Integrate your PaginatedList component into your main application component:

TypeScript
import React from 'react';
import PaginatedList from './PaginatedList';

function App() {
  return (
    <div className="App">
      <PaginatedList />
    </div>
  );
}

export default App;

In this example, the react-paginate library is used to create pagination controls that allow users to navigate through a list of items. The onPageChange callback handles the page change event, and the displayedItems array is calculated based on the current page and items per page.

Remember to adjust the component’s logic and styling to fit your specific use case and design preferences.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS