Skip to content

Commit

Permalink
[@mantine/carousel] Add dynamic slides handling (#2074)
Browse files Browse the repository at this point in the history
  • Loading branch information
rtivital committed Aug 12, 2022
1 parent f1cbf66 commit 969a3e5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
25 changes: 24 additions & 1 deletion src/mantine-carousel/src/Carousel.story.tsx
@@ -1,4 +1,5 @@
import React, { useRef } from 'react';
import React, { useRef, useState } from 'react';
import { Button } from '@mantine/core';
import Autoplay from 'embla-carousel-autoplay';
import { Carousel } from './Carousel';

Expand Down Expand Up @@ -70,3 +71,25 @@ export function AutoPlay() {
</div>
);
}

export function DynamicSlides() {
const [count, setCount] = useState(1);

const _slides = Array(count)
.fill(0)
.map((_, index) => (
<Carousel.Slide key={index} style={{ height: 200, background: 'pink', width: '100%' }}>
{index}
</Carousel.Slide>
));

return (
<div style={{ padding: 40, maxWidth: 500 }}>
<Carousel height={200} withIndicators>
{_slides}
</Carousel>
<Button onClick={() => setCount((c) => c + 1)}>Increment</Button>
<Button onClick={() => setCount((c) => c - 1)}>Decrement</Button>
</div>
);
}
13 changes: 12 additions & 1 deletion src/mantine-carousel/src/Carousel.tsx
@@ -1,5 +1,5 @@
/* eslint-disable react/no-unused-prop-types */
import React, { forwardRef, useEffect, useCallback, useState } from 'react';
import React, { forwardRef, useEffect, useCallback, useState, Children } from 'react';
import {
useComponentDefaultProps,
Box,
Expand All @@ -10,6 +10,7 @@ import {
StylesApiProvider,
Selectors,
} from '@mantine/core';
import { clamp } from '@mantine/hooks';
import useEmblaCarousel, { EmblaPluginType } from 'embla-carousel-react';
import { ForwardRefWithStaticComponents } from '@mantine/utils';
import { CarouselSlide, CarouselSlideStylesNames } from './CarouselSlide/CarouselSlide';
Expand Down Expand Up @@ -231,6 +232,16 @@ export const _Carousel = forwardRef<HTMLDivElement, CarouselProps>((props, ref)
return undefined;
}, [embla]);

useEffect(() => {
if (embla) {
embla.reInit();
setSlidesCount(embla.scrollSnapList().length);
setSelected((currentSelected) =>
clamp(currentSelected, 0, Children.toArray(children).length - 1)
);
}
}, [Children.toArray(children).length]);

const canScrollPrev = embla?.canScrollPrev() || false;
const canScrollNext = embla?.canScrollNext() || false;

Expand Down

0 comments on commit 969a3e5

Please sign in to comment.