I am trying to scroll to the bottom of an element when it loads. After searching on the web, I found this solution, but it is not working. Please point out the errors in my code.
"use client";
import { useEffect, useRef } from "react";
export default function TestPage() {
const scrollPage = useRef();
useEffect(() => {
scrollPage.current?.scrollIntoView({ behavior: "smooth", block: "end" });
}, [scrollPage]);
return (
<div className="h-[80vh] overflow-scroll" ref={scrollPage}>
<div className="h-[300vh]"></div>
<div>bottom</div>
</div>
);
}
3
Answers
The scrollIntoView method should be called on the last div element, not the container
using this above example something similar to this
Hope this helps
Issues in the Code
Incorrect use of scrollIntoView: The scrollIntoView method scrolls the element into the visible area of the browser window, but
since you want to scroll to the bottom of a scrollable container, you
should be using scrollTop instead.
Dependency Array in useEffect: The dependency array for useEffect should not include scrollPage. Instead, it should be an empty array
if you want the effect to run only once when the component mounts.
CSS Class: Ensure that your CSS classes are correctly applied and
that the outer div has a defined height and overflow properties to
allow scrolling.
Explanation of Changes
Scroll to Bottom: Instead of using scrollIntoView, we directly set scrollTop to scrollHeight, which effectively scrolls the element to its bottom.
Dependency Array: The dependency array is now empty ([]), ensuring that the effect runs only once when the component mounts, which is appropriate for this use case.
Remove
scrollPage
from the dependency array since you want to scroll when the page loads