Skip to content

Instantly share code, notes, and snippets.

@naramdash
Last active July 7, 2020 10:23
Show Gist options
  • Save naramdash/52386657ebcaf5b07dcd93fad1c9ad93 to your computer and use it in GitHub Desktop.
Save naramdash/52386657ebcaf5b07dcd93fad1c9ad93 to your computer and use it in GitHub Desktop.
React Fluent UI Pagination using Javascript & Fluent-UI
import React, { useMemo } from 'react';
import {
Stack,
Pivot,
PivotItem,
PivotLinkFormat,
IconButton,
} from '@fluentui/react';
function range(start, stop, step) {
return Array.from(
{ length: (stop - start) / step + 1 },
(_, i) => start + i * step,
);
}
export default function Pagination({
activePage,
setActivePage,
itemsCountPerPage,
totalItemsCount,
pageRangeDisplayed,
}) {
const { displayedPages, totalPageCount } = useMemo(() => {
const totalPageCount = Math.ceil(totalItemsCount / itemsCountPerPage);
const startDisplayedPage =
Math.floor((activePage - 1) / pageRangeDisplayed) * pageRangeDisplayed +
1;
const assumedEndDisplayedPage =
Math.floor((activePage - 1) / pageRangeDisplayed) * pageRangeDisplayed +
pageRangeDisplayed;
const endDisplayedPage =
assumedEndDisplayedPage > totalPageCount
? totalPageCount
: assumedEndDisplayedPage;
const displayedPages = range(startDisplayedPage, endDisplayedPage, 1);
return {
displayedPages,
totalPageCount,
};
}, [activePage, itemsCountPerPage, totalItemsCount, pageRangeDisplayed]);
return (
<Stack horizontal verticalAlign="center">
<IconButton
iconProps={{ iconName: 'Previous' }}
title="Previous"
ariaLabel="Previous"
onClick={() => setActivePage(1)}
/>
<IconButton
iconProps={{ iconName: 'Back' }}
title="Back"
ariaLabel="Back"
onClick={() => {
if (activePage > 1) setActivePage(activePage - 1);
}}
/>
<Pivot
selectedKey={activePage}
linkFormat={PivotLinkFormat.tabs}
onLinkClick={(pivotItem) => setActivePage(pivotItem.props.itemKey)}>
{displayedPages.map((displayedPage) => (
<PivotItem
key={displayedPage}
itemKey={displayedPage}
headerText={displayedPage}
/>
))}
</Pivot>
<IconButton
iconProps={{ iconName: 'Forward' }}
title="Forward"
ariaLabel="Forward"
onClick={() => {
if (activePage < totalPageCount) setActivePage(activePage + 1);
}}
/>
<IconButton
iconProps={{ iconName: 'Next' }}
title="Next"
ariaLabel="Next"
onClick={() => setActivePage(totalPageCount)}
/>
</Stack>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment