Created
March 14, 2024 06:11
-
-
Save LuisCardenasSolis/9db8aeadc5ce073d1b550c8566cf6c82 to your computer and use it in GitHub Desktop.
Carousel basic for Preact
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'preact/hooks' | |
function Carousel({ items = [], width = 'w-full' }) { | |
const [currentItem, setCurrentItem] = useState(0) | |
const handlePrevItem = () => { | |
if (currentItem === 0) return | |
setCurrentItem(currentItem - 1) | |
} | |
const handleNextItem = () => { | |
if (currentItem === items.length - 1) return | |
setCurrentItem(currentItem + 1) | |
} | |
return ( | |
<div data-carousel="slide" class={`flex flex-col gap-2 min-w-[300px] ${width}`}> | |
{/* Carousel wrapper */} | |
<div class="relative"> | |
<div class="overflow-hidden rounded-3xl pointer-events-none" data-carousel-item> | |
{items.map((img, index) => ( | |
<img | |
src={img.src} | |
alt={`Slide ${index}`} | |
class={`w-full h-auto object-cover ${currentItem !== index ? 'hidden' : 'block'}`} | |
/> | |
))} | |
</div> | |
<div | |
type="button" | |
class="absolute top-0 start-0 flex items-center h-full pl-4 cursor-pointer" | |
data-carousel-prev> | |
<button | |
type="button" | |
class="bg-[#00000041] text-primary-500 rounded-full size-7 p-[6px]" | |
onClick={handlePrevItem}> | |
<svg class="size-full" fill="none" viewBox="0 0 7 10" aria-hidden="true"> | |
<path | |
stroke="currentColor" | |
stroke-linecap="round" | |
stroke-linejoin="round" | |
stroke-width="2" | |
d="M5 1 1 5l4 4"></path> | |
</svg> | |
</button> | |
</div> | |
<div | |
type="button" | |
class="absolute top-0 end-0 flex items-center h-full pr-4 cursor-pointer" | |
data-carousel-next> | |
<button | |
type="button" | |
class="bg-[#00000041] text-primary-500 rounded-full size-7 p-[6px]" | |
onClick={handleNextItem}> | |
<svg class="size-full" fill="none" viewBox="0 0 5 10" aria-hidden="true"> | |
<path | |
stroke="currentColor" | |
stroke-linecap="round" | |
stroke-linejoin="round" | |
stroke-width="2" | |
d="m1 9 4-4-4-4"></path> | |
</svg> | |
</button> | |
</div> | |
</div> | |
{/* Slider indicators */} | |
<div class="flex justify-center gap-2"> | |
{items.map((_, index) => ( | |
<span | |
class={`size-3 rounded-full border border-primary-500 ${currentItem === index ? 'bg-primary-500' : 'bg-transparent'}`}></span> | |
))} | |
</div> | |
</div> | |
) | |
} | |
export default Carousel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment