From a1025d507bea0f1d1cc33a29c5ea2201f73be1f0 Mon Sep 17 00:00:00 2001 From: Catalin Pinte <1243434+cond0r@users.noreply.github.com> Date: Thu, 22 Dec 2022 09:39:18 +0200 Subject: [PATCH] Update ProductSlider.tsx --- .../product/ProductSlider/ProductSlider.tsx | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/site/components/product/ProductSlider/ProductSlider.tsx b/site/components/product/ProductSlider/ProductSlider.tsx index 612068502..486714986 100644 --- a/site/components/product/ProductSlider/ProductSlider.tsx +++ b/site/components/product/ProductSlider/ProductSlider.tsx @@ -10,6 +10,8 @@ import cn from 'clsx' import { a } from '@react-spring/web' import s from './ProductSlider.module.css' import ProductSliderControl from '../ProductSliderControl' +import { useProduct } from '../context' +import { Image as ProductImage } from '@commerce/types/common' interface ProductSliderProps { children?: React.ReactNode[] @@ -20,7 +22,9 @@ const ProductSlider: React.FC = ({ children, className = '', }) => { + const { product, variant } = useProduct() const [currentSlide, setCurrentSlide] = useState(0) + const sliderContainerRef = useRef(null) const thumbsContainerRef = useRef(null) @@ -30,7 +34,6 @@ const ProductSlider: React.FC = ({ slideChanged(s) { const slideNumber = s.track.details.rel setCurrentSlide(slideNumber) - if (thumbsContainerRef.current) { const $el = document.getElementById(`thumb-${slideNumber}`) if (slideNumber >= 3) { @@ -42,6 +45,18 @@ const ProductSlider: React.FC = ({ }, }) + useEffect(() => { + const index = product.images.findIndex((image: ProductImage) => { + return image.url === variant?.image?.url + }) + + if (index !== -1) { + slider.current?.moveToIdx(index, false, { + duration: 0, + }) + } + }, [variant, product, slider]) + // Stop the history navigation gesture on touch devices useEffect(() => { const preventNavigation = (event: TouchEvent) => { @@ -72,8 +87,13 @@ const ProductSlider: React.FC = ({ } }, []) - const onPrev = React.useCallback(() => slider.current?.prev(), [slider]) - const onNext = React.useCallback(() => slider.current?.next(), [slider]) + const onPrev = React.useCallback(() => { + slider.current?.prev() + }, [slider]) + + const onNext = React.useCallback(() => { + slider.current?.next() + }, [slider]) return (