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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay