From 09587e10b13a146234913c43b308e5cd5f9c1fb3 Mon Sep 17 00:00:00 2001 From: Hyungu Kang | Airen Date: Wed, 7 Aug 2024 14:51:11 +0900 Subject: [PATCH] [AC-3508] fix: update carousel index calculation (#327) ## Changes - Bugfix for carousel index calculation ticket: [AC-3508] [AC-3508]: https://sendbird.atlassian.net/browse/AC-3508?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ --- src/components/ui/SnapCarousel/index.tsx | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/components/ui/SnapCarousel/index.tsx b/src/components/ui/SnapCarousel/index.tsx index b88de3926..b80d089df 100644 --- a/src/components/ui/SnapCarousel/index.tsx +++ b/src/components/ui/SnapCarousel/index.tsx @@ -59,13 +59,14 @@ export const SnapCarousel = ({ const ref = useRef(null); const [activeIndex, setActiveState] = useState(0); const itemLength = React.Children.toArray(children).length; - const cursorSize = useMemo(() => { - const containerWidth = (ref.current?.scrollWidth ?? 0) - startPadding; - return containerWidth / itemLength + gap; - }, [ref.current?.scrollWidth, itemLength, gap, startPadding]); + + const itemWidth = useMemo(() => { + const total = ref.current?.scrollWidth ?? 0; + return total - (startPadding + endPadding + gap * (itemLength - 1)) / itemLength; + }, [ref.current?.scrollWidth, itemLength, gap, startPadding, endPadding]); const onScroll = (e: React.UIEvent) => { - const idx = Math.round(e.currentTarget.scrollLeft / cursorSize); + const idx = Math.round(e.currentTarget.scrollLeft / itemWidth); if (idx !== activeIndex) setActiveState(idx); }; @@ -73,7 +74,7 @@ export const SnapCarousel = ({ if (ref.current) { const nextIdx = Math.min(Math.max(0, index), itemLength - 1); ref.current.scroll({ - left: nextIdx * cursorSize, + left: nextIdx * itemWidth, behavior: 'smooth', }); }