mue/src/components/helpers/carousel/Carousel.jsx

81 lines
2.1 KiB
React
Raw Normal View History

2022-10-30 16:56:26 +00:00
import React, { useState, useEffect, useCallback, useRef, memo } from 'react';
import { MdOutlineArrowForwardIos, MdOutlineArrowBackIos } from 'react-icons/md';
2022-08-07 17:36:56 +00:00
import useEmblaCarousel from 'embla-carousel-react';
import Autoplay from 'embla-carousel-autoplay';
2022-08-07 17:36:56 +00:00
import './carousel.scss';
2022-10-30 16:56:26 +00:00
function EmblaCarousel({ data }) {
2022-08-02 18:32:13 +00:00
const autoplay = useRef(
2022-08-07 17:36:56 +00:00
Autoplay({ delay: 3000, stopOnInteraction: false }, (emblaRoot) => emblaRoot.parentElement),
2022-08-02 18:32:13 +00:00
);
const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false }, [autoplay.current]);
2022-08-02 18:32:13 +00:00
const [prevBtnEnabled, setPrevBtnEnabled] = useState(false);
const [nextBtnEnabled, setNextBtnEnabled] = useState(false);
const scroll = useCallback(
(direction) => {
if (!emblaApi) {
return;
}
2022-08-02 18:32:13 +00:00
if (direction === 'next') {
emblaApi.scrollNext();
} else {
emblaApi.scrollPrev();
}
autoplay.current.reset();
},
[emblaApi],
);
2022-08-02 18:32:13 +00:00
const onSelect = useCallback(() => {
if (!emblaApi) {
return;
}
2022-08-02 18:32:13 +00:00
setPrevBtnEnabled(emblaApi.canScrollPrev());
setNextBtnEnabled(emblaApi.canScrollNext());
}, [emblaApi]);
useEffect(() => {
if (!emblaApi) {
return;
}
2022-08-02 18:32:13 +00:00
onSelect();
2022-08-07 17:36:56 +00:00
emblaApi.on('select', onSelect);
2022-08-02 18:32:13 +00:00
}, [emblaApi, onSelect]);
return (
2022-08-31 21:21:37 +00:00
<div className="carousel">
<div className="carousel_viewport" ref={emblaRef}>
<div className="carousel_container">
2022-08-02 18:32:13 +00:00
{data.map((photo, index) => (
2022-08-31 21:21:37 +00:00
<div className="carousel_slide" key={index}>
2022-08-31 21:24:01 +00:00
<div className="carousel_slide_inner">
2022-11-06 11:59:59 +00:00
<img src={photo.url.default} alt="Marketplace example screenshot" />
2022-08-02 18:32:13 +00:00
</div>
</div>
))}
</div>
</div>
<button
2022-08-31 21:21:37 +00:00
className="carousel_button prev"
onClick={() => scroll('prev')}
disabled={!prevBtnEnabled}
>
<MdOutlineArrowBackIos />
</button>
<button
2022-08-31 21:21:37 +00:00
className="carousel_button next"
onClick={() => scroll('next')}
disabled={!nextBtnEnabled}
>
<MdOutlineArrowForwardIos />
</button>
</div>
);
}
2022-10-30 16:56:26 +00:00
2022-11-06 11:59:59 +00:00
export default memo(EmblaCarousel);