23 lines
783 B
TypeScript
23 lines
783 B
TypeScript
import {useEffect, useRef} from "react";
|
|
|
|
/**
|
|
* A React component that automatically scrolls itself into view whenever rendered.
|
|
*
|
|
* This component is especially useful in scrollable containers to keep the most
|
|
* recent content visible (e.g., chat applications, live logs, or notifications).
|
|
*
|
|
* It uses the browser's `Element.scrollIntoView()` API with smooth scrolling behavior.
|
|
*
|
|
* @returns A `<div>` element that scrolls into view when mounted or updated.
|
|
*/
|
|
export default function ScrollIntoView() {
|
|
/** Ref to the DOM element that will be scrolled into view. */
|
|
const elementRef = useRef<HTMLDivElement>(null);
|
|
|
|
useEffect(() => {
|
|
if (elementRef.current) elementRef.current.scrollIntoView({ behavior: "smooth" });
|
|
});
|
|
|
|
return <div ref={elementRef} />;
|
|
}
|