diff --git a/src/index.js b/src/index.js index 35189787..0fed3bae 100644 --- a/src/index.js +++ b/src/index.js @@ -4,6 +4,7 @@ import shallowequal from 'shallowequal' import raf from 'raf' import shouldUpdate from './shouldUpdate' +export { default as useHeadroom } from "./useHeadroom"; const noop = () => {} export default class Headroom extends Component { @@ -345,4 +346,4 @@ export default class Headroom extends Component { ) } -} +} \ No newline at end of file diff --git a/src/shouldUpdate.js b/src/shouldUpdate.js index 4b2c883e..3c72ba7b 100644 --- a/src/shouldUpdate.js +++ b/src/shouldUpdate.js @@ -84,4 +84,4 @@ export default function ( distanceScrolled, } } -} +} \ No newline at end of file diff --git a/src/useHeadroom.js b/src/useHeadroom.js new file mode 100644 index 00000000..c0d54c88 --- /dev/null +++ b/src/useHeadroom.js @@ -0,0 +1,28 @@ +import React from "react"; + +export default ({ onPin, onUnpin }) => { + const [scroll, setScroll] = React.useState(0); + + // Tracking scroll value + React.useEffect(() => { + const handleScroll = () => setScroll(window.scrollY); + window.addEventListener("scroll", handleScroll); + // Cleanup function + return () => window.removeEventListener("scroll", handleScroll); + }, []); + + const scrollRef = React.useRef({ scroll: scroll }); + + // Handling onPin and onUnpin callbacks + React.useEffect(() => { + if (onPin && scrollRef.current.scroll <= scroll) onPin(); + if (onUnpin && scrollRef.current.scroll > scroll) onUnpin(); + }, [scrollRef.current.scroll <= scroll]); + + // Handling the backward scroll behavior + React.useEffect(() => { + scrollRef.current.scroll = scroll; + }, [scroll]); + + return scrollRef.current.scroll > scroll || scroll === 0; +}; diff --git a/test/calc.js b/test/calc.js index 894d161d..e5a27613 100644 --- a/test/calc.js +++ b/test/calc.js @@ -196,4 +196,4 @@ describe('shouldUpdate', () => { const result = shouldUpdate(100, 110, propDefaults, state) expect(result.action).to.equal('unpin-snap') }) -}) +}) \ No newline at end of file