/AtmPotterTravelling
Created 1 year, 10 months ago...
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
import { useState, useEffect } from 'react'
import {Right, Left} from './icons'
const Caraousel = ({ images }: { images: Array<string>}) => {
const [current, setCurrent] = useState(0)
const [touchStartX, setTouchStartX] = useState(0)
const [touchEndX, setTouchEndX] = useState(0)
const previousSlide = () => {
setCurrent(prevIndex => (prevIndex - 1 + images.length) % images.length)
}
const nextSlide = () => {
setCurrent(prevIndex => (prevIndex + 1) % images.length)
}
const handleTouchEnd = (e: React.TouchEvent<HTMLDivElement>) => {
const touchDiff = touchEndX - touchStartX
if(touchDiff > 50) {
previousSlide()
} else if (touchDiff < -50) {
nextSlide()
}
setTouchStartX(0)
setTouchEndX(0)
}
useEffect(() => {
const interval = setInterval(() => {
setCurrent(prevIndex => (prevIndex + 1) % images.length)
},5000)
return () => clearInterval(interval)
},[images.length])
return (
<div className='relative h-screen w-screen p-8' onTouchStart={e => setTouchStartX(e.touches[0].clientX)} onTouchMove={e => setTouchEndX(e.touches[0].clientX)} onTouchEnd={handleTouchEnd}>
<button className='absolute top-1/2 left-4 translate-y-1/2 p-4 z-[2] text-white/50 bg-black/10 hover:text-white hover:bg-black/20' onClick={previousSlide}><Left className='h-[1.5em]' /></button>
<button className='absolute top-1/2 right-4 translate-y-1/2 p-4 z-[2] text-white/50 bg-black/10 hover:text-white hover:bg-black/20' onClick={nextSlide}><Right className='h-[1.5em]' /></button>
<ul>
{images.map((image, index) => (
<li className={`absolute inset-0 opacity-0 ${current === index && 'opacity-100'} transition-opacity ease-in-out duration-200`} key={index} data-active>
<img src={image} alt={`Caraousel Slide ${index + 1}`} className='w-full h-full object-cover object-center' loading='lazy' />
</li>
))}
</ul>
</div>
)
}
export default Caraousel