DEV Community

Prodipta Banerjee
Prodipta Banerjee

Posted on

1

Reusable pagination component using hook

Create a hook for pagination like this

import { useState } from "react";

export default function usePagination() {
    const [offset, setOffset] = useState(0);
    const [limit, setLimit] = useState(10);

    function changeOffset(offsetParam: number) {
        setOffset(offsetParam);
    }
    function changeLimit(limitParam: number) {
        setLimit(limitParam);
    }
Enter fullscreen mode Exit fullscreen mode

This is the reusable pagination component UI,

type TypeProps = {
count: number;
changeOffset: (offset: number) => void;
offset: number;
limit: number;
};

const Pagination = (props: TypeProps) => {
const { count, changeOffset, offset, limit } = props;

let startingItemNumber = offset + 1;
let endingItemNumber = offset + limit > count ? count : offset + limit;

return (
<div>
  <p>Showing {startingItemNumber} to {endingItemNumber} of {count} entries
   </p>
   <button onClick={() => changeOffset(offset - limit)} disabled= 
     {offset === 0} >
    Prev
   </button>
   <button onClick={() => changeOffset(offset + limit)} 
      disabled={endingItemNumber === count}>
    Next
   </button>
</div>
  );
};

export default Pagination;

Enter fullscreen mode Exit fullscreen mode

Use the pagination hook and the pagination component like this in your page


const List = () => {
const { limit, offset, changeOffset } = usePagination();
//_e.g. usage of the pagination hook _
const { data, isLoading } = useGetList(limit, offset);


return (
<>
//_Populate list_

 <Pagination
  //make sure count, offset and limit is Number type
  count={data.count}
  offset={data.offset}
  limit={data.limit}
  changeOffset={changeOffset}
 />
<>
)

export default List;

Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay