Last active
March 2, 2019 18:26
-
-
Save andrzejewsky/08d9a28be580caefaf2ed1269e91bcc8 to your computer and use it in GitHub Desktop.
Netflix slider sliding hook
This file contains hidden or 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, useRef, useEffect } from 'react' | |
const PADDINGS = 110; | |
const useSliding = (elementWidth, countElements) => { | |
const containerRef = useRef(null); | |
const [containerWidth, setContainerWidth] = useState(0); | |
const [distance, setDistance] = useState(0); | |
const [totalInViewport, setTotalInViewport] = useState(0) | |
const [viewed, setViewed] = useState(0); | |
useEffect(() => { | |
const containerWidth = containerRef.current.clientWidth - PADDINGS; | |
setContainerWidth(containerWidth); | |
setTotalInViewport(Math.floor(containerWidth / elementWidth)); | |
}, [containerRef.current]); | |
const handlePrev = () => { | |
setViewed(viewed - totalInViewport); | |
setDistance(distance + containerWidth); | |
} | |
const handleNext = () => { | |
setViewed(viewed + totalInViewport); | |
setDistance(distance - containerWidth) | |
} | |
const slideProps = { | |
style: { transform: `translate3d(${distance}px, 0, 0)` } | |
}; | |
const hasPrev = distance < 0; | |
const hasNext = (viewed + totalInViewport) < countElements; | |
return { handlePrev, handleNext, slideProps, containerRef, hasPrev, hasNext }; | |
} | |
export default useSliding; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment