Skip to content
This repository has been archived by the owner on Aug 31, 2022. It is now read-only.

Commit

Permalink
fix(carousel): fixed the scroll witdh of the carousel
Browse files Browse the repository at this point in the history
  • Loading branch information
fritzschoff committed Mar 30, 2022
1 parent e0e2a99 commit 56467b4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 22 deletions.
34 changes: 14 additions & 20 deletions src/components/Carousel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default function Carousel({
}
if (ltr) {
setActiveIndex((state) => {
if (state >= carouselItems.length) return state;
if (state >= carouselItems.length - 1) return state;
scroll(state + 1);
return state + 1;
});
Expand All @@ -70,20 +70,19 @@ export default function Carousel({
const ref = styledCarouselItemsWrapperRef.current!;
setRefWidth((_) => {
const initState = document
.getElementById(CHILDREN_ID_PREFIX.concat(activeIndex.toString()))!
.getElementById(CHILDREN_ID_PREFIX.concat((activeIndex - 1).toString()))!
.getBoundingClientRect().width;
const calculatedOffset = updatedCarouselItems
.slice(0, activeIndex)
.reduce((acc, _, index) => {
return (
acc +
document.getElementById(CHILDREN_ID_PREFIX.concat(index.toString()))!.clientWidth
);
}, 0);
ref.scroll({
behavior: 'smooth',
left: calculatedOffset - ref.clientWidth / 2 - initState / 2,
});
if (carouselItems.length % 2 === 0) {
ref.scroll({
behavior: 'smooth',
left: ref.scrollWidth / 2 - ref.clientWidth / 2,
});
} else {
ref.scroll({
behavior: 'smooth',
left: ref.scrollWidth / 2 - ref.clientWidth / 2 + initState / 2,
});
}
return initState;
});
}
Expand All @@ -102,14 +101,9 @@ export default function Carousel({
left: 0,
});
}
const calculatedOffset = updatedCarouselItems.slice(0, newIndex).reduce((acc, _, index) => {
return (
acc + document.getElementById(CHILDREN_ID_PREFIX.concat(index.toString()))!.clientWidth
);
}, 0);
ref.scroll({
behavior: 'smooth',
left: calculatedOffset - ref.clientWidth / 2 - refWidth / 2,
left: refWidth * newIndex - ref.clientWidth / 2 - refWidth / 2,
});
};

Expand Down
6 changes: 4 additions & 2 deletions src/stories/Carousel.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ Template.args = {
}}
>
8
</div> /*
</div>,
<div
key={10}
style={{
Expand All @@ -122,6 +122,7 @@ Template.args = {
>
9
</div>,

<div
key={10}
style={{
Expand All @@ -133,6 +134,7 @@ Template.args = {
}}
>
10
</div>, */,
</div>,
,
],
};

0 comments on commit 56467b4

Please sign in to comment.