Skip to content

Instantly share code, notes, and snippets.

@andrzejewsky
Last active March 2, 2019 18:26
Show Gist options
  • Save andrzejewsky/08d9a28be580caefaf2ed1269e91bcc8 to your computer and use it in GitHub Desktop.
Save andrzejewsky/08d9a28be580caefaf2ed1269e91bcc8 to your computer and use it in GitHub Desktop.
Netflix slider sliding hook
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