Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Created February 19, 2019 17:42
Show Gist options
  • Save DroopyTersen/4641a8f13d52b55bd39746de46fd360d to your computer and use it in GitHub Desktop.
Save DroopyTersen/4641a8f13d52b55bd39746de46fd360d to your computer and use it in GitHub Desktop.
import { useEffect, useState } from "react";
import usePaging from "./usePaging";
import useHover from "./useHover";
import useInterval from "./useInterval";
export default function useAutoPaging(
totalPages: number,
delay = 5000,
defaultPage = 1
) {
let { currentPage, goForward, goBack, goTo } = usePaging(
totalPages,
defaultPage
);
let [pageDelay, setPageDelay] = useState(delay);
let [hoverRef, isHovered] = useHover();
// If the caller updates the delay prop, update state
useEffect(
() => {
setPageDelay(delay);
},
[delay]
);
// Start by setting delay to the prop given by caller
const start = () => setPageDelay(delay);
// Stop by setting the delay to 0.
const stop = () => setPageDelay(0);
useEffect(
() => {
if (isHovered) stop();
else start();
},
[isHovered]
);
// Call goForward (method from usePaging) every N milliseconds
useInterval(goForward, pageDelay);
// return the usePaging stuff, plus the ref that the caller can use to
// decide which dom element should pause the paging on hover.
return {
currentPage,
goForward,
goBack,
pauseRef: hoverRef as React.MutableRefObject<any>,
goTo
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment