Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Created February 19, 2019 17:17
Show Gist options
  • Save DroopyTersen/4ffb1543149f567a5173c6fdea22b25b to your computer and use it in GitHub Desktop.
Save DroopyTersen/4ffb1543149f567a5173c6fdea22b25b to your computer and use it in GitHub Desktop.
Composing Behavior with React hooks - usePaging
import { useState } from "react";
export default function usePaging(totalPages: number, defaultPage = 1) {
let [currentPage, setCurrentPage] = useState(defaultPage);
let goBack = () => {
let newPage = currentPage - 1;
if (newPage < 1) newPage = totalPages;
setCurrentPage(newPage);
};
let goForward = () => {
let newPage = currentPage + 1;
if (newPage > totalPages) newPage = 1;
setCurrentPage(newPage);
};
let goTo = (pageNumber: number) => {
if (pageNumber > totalPages) pageNumber = totalPages;
if (pageNumber < 1) pageNumber = 1;
setCurrentPage(pageNumber);
};
return {
currentPage,
goForward,
goBack,
goTo
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment