Skip to content

Instantly share code, notes, and snippets.

@Rieranthony
Created August 2, 2024 11:51
Show Gist options
  • Select an option

  • Save Rieranthony/196ac7294937b10e25262ff5bbfcd23c to your computer and use it in GitHub Desktop.

Select an option

Save Rieranthony/196ac7294937b10e25262ff5bbfcd23c to your computer and use it in GitHub Desktop.
Scrollable component with UI clue (React + TailwindCss)
import React, { useRef, useEffect, useState, ReactNode } from "react";
import { cn } from "@/libs/utils";
interface ScrollableWithGradientProps {
children: ReactNode;
className?: string;
containerClassName?: string;
gradientClassName?: string;
maxHeight?: string;
}
export function Scrollable({
children,
className,
containerClassName,
gradientClassName,
maxHeight = "11rem",
}: ScrollableWithGradientProps) {
const scrollableRef = useRef<HTMLDivElement>(null);
const [showGradient, setShowGradient] = useState(true);
useEffect(() => {
const handleScroll = () => {
if (scrollableRef.current) {
const { scrollTop, scrollHeight, clientHeight } = scrollableRef.current;
setShowGradient(scrollTop + clientHeight < scrollHeight - 10);
}
};
const scrollableElement = scrollableRef.current;
if (scrollableElement) {
scrollableElement.addEventListener("scroll", handleScroll);
handleScroll(); // Check initial state
}
return () => {
if (scrollableElement) {
scrollableElement.removeEventListener("scroll", handleScroll);
}
};
}, []);
return (
<div className={cn("relative", containerClassName)}>
<div
ref={scrollableRef}
className={cn(
"overflow-y-auto rounded bg-os-background-200 p-4 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-primary/20 scrollbar-thumb-rounded-md dark:bg-os-background-800",
className,
)}
style={{ maxHeight }}
>
{children}
</div>
{showGradient && (
<div
className={cn(
"pointer-events-none absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-os-background-200 to-transparent dark:from-os-background-800",
gradientClassName,
)}
/>
)}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment