Published on

React Tips: Scroll to the bottom

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

Make a scrollable component automatically scroll to the bottom whenever its content changes.

Implementation in React

import React, { useEffect, useRef } from "react";

const AutoScrollDiv = ({ children }: { children: React.ReactNode }) => {
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [children]); // Run the effect whenever the content changes

  return (
    <div
      className="flex-1 overflow-y-auto"
      ref={scrollRef}
    >
      {children}
    </div>
  );
};

export default AutoScrollDiv;