Last active
November 14, 2024 09:52
-
-
Save nimone/1fad7ac88bf2a5b07a26eb45134c76a6 to your computer and use it in GitHub Desktop.
Build a carousel component like instagram purely in ReactJS and TailwindCSS
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, useEffect } from "react" | |
import { ChevronLeft, ChevronRight } from "react-feather" | |
export default function Carousel({ | |
children: slides, | |
autoSlide = false, | |
autoSlideInterval = 3000, | |
}) { | |
const [curr, setCurr] = useState(0) | |
const prev = () => | |
setCurr((curr) => (curr === 0 ? slides.length - 1 : curr - 1)) | |
const next = () => | |
setCurr((curr) => (curr === slides.length - 1 ? 0 : curr + 1)) | |
useEffect(() => { | |
if (!autoSlide) return | |
const slideInterval = setInterval(next, autoSlideInterval) | |
return () => clearInterval(slideInterval) | |
}, []) | |
return ( | |
<div className="overflow-hidden relative"> | |
<div | |
className="flex transition-transform ease-out duration-500" | |
style={{ transform: `translateX(-${curr * 100}%)` }} | |
> | |
{slides} | |
</div> | |
<div className="absolute inset-0 flex items-center justify-between p-4"> | |
<button | |
onClick={prev} | |
className="p-1 rounded-full shadow bg-white/80 text-gray-800 hover:bg-white" | |
> | |
<ChevronLeft size={40} /> | |
</button> | |
<button | |
onClick={next} | |
className="p-1 rounded-full shadow bg-white/80 text-gray-800 hover:bg-white" | |
> | |
<ChevronRight size={40} /> | |
</button> | |
</div> | |
<div className="absolute bottom-4 right-0 left-0"> | |
<div className="flex items-center justify-center gap-2"> | |
{slides.map((_, i) => ( | |
<div | |
className={` | |
transition-all w-3 h-3 bg-white rounded-full | |
${curr === i ? "p-2" : "bg-opacity-50"} | |
`} | |
/> | |
))} | |
</div> | |
</div> | |
</div> | |
) | |
} |
ts version with vite support
https://gist.github.com/Hachikoi-the-creator/4d9ff83a2021fcb1596907d85be1eeb5
thx for this!!! 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this gist, it works perfectly 🙏👍