Add Scroll to Top functionality inside shadcn's <ScrollArea/> component

shawon

Shawon Saha

Posted on April 7, 2024

Add Scroll to Top functionality inside shadcn's <ScrollArea/> component

The <ScrollArea/> component from shadcn's UI library provides an elegant scrolling experience, but it doesn't include built-in functionality for scrolling to the top of the content area. In this post, we'll walk through how to add a "Scroll to Top" button that smoothly scrolls the <ScrollArea/> to its beginning.

Step 1: Import useRef from React

import { useRef } from "react";
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a ref for the <ScrollArea/>

const scrollAreaRef = useRef<HTMLDivElement | null>(null);
Enter fullscreen mode Exit fullscreen mode

This line creates a mutable ref object that will hold a reference to the <ScrollArea/> div element.

Step 3: Attach the ref to the top <div>

<div ref={scrollAreaRef}>
  {/* ScrollArea content goes here */}
</div>
Enter fullscreen mode Exit fullscreen mode

Scroll to top ShadCN
Just like this

Step 4: Define the triggerScrollToTop function

const triggerScrollToTop = () => {
  if (scrollAreaRef.current) {
    scrollAreaRef.current.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    });
  }
};
Enter fullscreen mode Exit fullscreen mode

This function checks if scrollAreaRef.current has a value (i.e., if the <ScrollArea/> has mounted). If so, it calls the scrollIntoView method on the element, passing options to ensure smooth scrolling to the top.

Step 5: Add a "Scroll to Top" button

<button
  onClick={triggerScrollToTop}
>
  Scroll to Top
</button>
Enter fullscreen mode Exit fullscreen mode

Finally, render a button that calls triggerScrollToTop when clicked. Adjust the styling and placement as desired.

And that's it! With these steps, you've added smooth scroll-to-top functionality to shadcn's <ScrollArea/> component using just a few lines of React code.

💖 💪 🙅 🚩
shawon
Shawon Saha

Posted on April 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related