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);
}
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;
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;
Top comments (0)