Created
February 19, 2019 17:17
-
-
Save DroopyTersen/4ffb1543149f567a5173c6fdea22b25b to your computer and use it in GitHub Desktop.
Composing Behavior with React hooks - usePaging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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