Created
September 14, 2023 20:48
-
-
Save Renanf68/9291bae9545a9061e1b8a9d72099fdb7 to your computer and use it in GitHub Desktop.
Basic react carousel with tailwind and lucide-react
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
"use client"; | |
import { ChevronLeft, ChevronRight } from "lucide-react"; | |
import React from "react"; | |
interface CarouselProps { | |
itemHeight: number; | |
scrollSize?: number; | |
children: React.ReactNode; | |
} | |
export const Carousel = ({ | |
itemHeight, | |
scrollSize = 400, | |
children, | |
}: CarouselProps) => { | |
const [leftScroll, setLeftScroll] = React.useState(false); | |
const areaRef = React.useRef<HTMLDivElement>(null); | |
const top = itemHeight / 2 - 10; | |
const handleScroll = (dir: "left" | "right") => { | |
if (!areaRef.current) return; | |
const delta = scrollSize * (dir === "right" ? 1 : -1); | |
const scroll = areaRef.current.scrollLeft + delta; | |
setLeftScroll(scroll > 0); | |
areaRef.current.scroll({ left: scroll, behavior: "smooth" }); | |
}; | |
return ( | |
<div className="relative"> | |
<div ref={areaRef} className="flex gap-4 py-2 overflow-auto no-scrollbar"> | |
{children} | |
</div> | |
<div | |
data-active={leftScroll} | |
className="hidden data-[active=true]:lg:flex absolute left-4 cursor-pointer justify-center items-center w-10 h-10 rounded-full border-input bg-white" | |
style={{ | |
top: `${top}px`, | |
}} | |
> | |
<ChevronLeft | |
onClick={() => handleScroll("left")} | |
className="w-5 h-5 text-neutral-800" | |
/> | |
</div> | |
<div | |
onClick={() => handleScroll("right")} | |
className="hidden lg:flex absolute right-4 cursor-pointer justify-center items-center w-10 h-10 rounded-full border-input bg-white" | |
style={{ | |
top: `${top}px`, | |
}} | |
> | |
<ChevronRight className="w-5 h-5 text-neutral-800" /> | |
</div> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment