Skip to content

Commit

Permalink
handle pagination on mobile
Browse files Browse the repository at this point in the history
  • Loading branch information
krystonen committed Oct 1, 2024
1 parent 5b7d59b commit 5a87381
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
21 changes: 21 additions & 0 deletions packages/react-pagination/hooks/usePagination.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,27 @@ describe("usePagination ", () => {

expect(result.current.page).toBe(1);
});

it("should handle mobile view: only show 1 boundaries", () => {
const { result } = renderHook(() =>
usePagination({
pages: 20,
initialPage: 1,
siblings: 1,
boundaries: 2,
isMobile: true,
}),
);

expect(result.current.range).toEqual([[1, 2, 3], [20]]);

act(() => {
result.current.setPage(2);
});

// // The layout of the segments should still be the same.
expect(result.current.range).toEqual([[1, 2, 3], [20]]);
});
});

describe("Array-based pagination", () => {
Expand Down
28 changes: 21 additions & 7 deletions packages/react-pagination/hooks/usePagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ interface UsePaginationBaseProps {
boundaries: number;

gapSize?: number;
isMobile?: boolean;
}

export interface UsePaginationWithPagesProps extends UsePaginationBaseProps {
Expand Down Expand Up @@ -101,25 +102,38 @@ export function usePagination<T>(
[clampIndex],
);

const { boundaries = 1, siblings = 1, gapSize = 1 } = props;
const { boundaries = 1, siblings = 1, gapSize = 1, isMobile = false } = props;

const responsiveSiblings = isMobile ? 0 : siblings;
const responsiveBoundaries = isMobile ? 1 : boundaries;

const range = useMemo(() => {
const segments: [number[], number[], number[]] = [
boundaries ? clampedSequence(1, boundaries) : [],
clampedSequence(page - siblings, page + siblings),
boundaries
? clampedSequence(computedPages + 1 - boundaries, computedPages)
clampedSequence(page - responsiveSiblings, page + responsiveSiblings),
responsiveBoundaries
? clampedSequence(
computedPages + 1 - responsiveBoundaries,
computedPages,
)
: [],
];

return formatSegments(
segments,
computedPages,
siblings,
boundaries,
responsiveSiblings,
responsiveBoundaries,
gapSize,
);
}, [page, boundaries, siblings, clampedSequence, computedPages, gapSize]);
}, [

Check warning on line 129 in packages/react-pagination/hooks/usePagination.ts

View workflow job for this annotation

GitHub Actions / check / Check Quality

React Hook useMemo has a missing dependency: 'boundaries'. Either include it or remove the dependency array
page,
responsiveBoundaries,
responsiveSiblings,
clampedSequence,
computedPages,
gapSize,
]);

const currentItems = useMemo(
() =>
Expand Down

0 comments on commit 5a87381

Please sign in to comment.