37 lines
1.3 KiB
React
37 lines
1.3 KiB
React
import React, { useState, useEffect } from 'react';
|
||
import './Carousel.css';
|
||
|
||
export default function Carousel({ items = [], autoplay = true, interval = 3000, onChange }) {
|
||
const [index, setIndex] = useState(0);
|
||
const len = items.length || 1;
|
||
|
||
function go(i) {
|
||
const next = (i + len) % len;
|
||
setIndex(next);
|
||
onChange && onChange(next);
|
||
}
|
||
useEffect(() => {
|
||
if (!autoplay || items.length < 2) return;
|
||
const t = setInterval(() => go(index + 1), interval);
|
||
return () => clearInterval(t);
|
||
// eslint-disable-next-line
|
||
}, [index, autoplay, interval, items.length]);
|
||
|
||
return (
|
||
<div className="aa-carousel">
|
||
<div className="aa-carousel-track" style={{ transform: `translateX(-${index * 100}%)` }}>
|
||
{items.map((s, i) => (
|
||
<div className="aa-carousel-slide" key={i} style={{ background: s.color }}>{s.text}</div>
|
||
))}
|
||
</div>
|
||
<button className="aa-carousel-arrow prev" onClick={() => go(index - 1)}>‹</button>
|
||
<button className="aa-carousel-arrow next" onClick={() => go(index + 1)}>›</button>
|
||
<div className="aa-carousel-dots">
|
||
{items.map((_, i) => (
|
||
<span key={i} className={'aa-carousel-dot' + (i === index ? ' is-active' : '')} onClick={() => go(i)} />
|
||
))}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|