How can I scroll to the top in a Modal component in React?

Viewed 52

This is the code to scroll to the top.

const ScrollToTop = () => {
    const [showTopBtn, setShowTopBtn] = useState(false);
    useEffect(() => {
        window.addEventListener("scroll", () => {
            if (window.scrollY > 400) {
                setShowTopBtn(true);
            } else {
                setShowTopBtn(false);
            }
        });
    }, []);
    const goToTop = () => {
        window.scrollTo({
            top: 0,
            behavior: "smooth",
        });
    };
    return (
        <div className="top-to-btm">
            {" "}
            {showTopBtn && (
                <FaAngleUp
                    className="icon-position icon-style"
                    onClick={goToTop}
                />
            )}{" "}
        </div>
    );
};

This works fine in a normal window, but in a React Modal it doesn't. What do I have to change to make in work in a Modal. Any help is appreciated.

1 Answers

So, instead of window.scrollTop, you need to get the modal container element ( which has the scroll behavior ), maybe with template ref, then use element.scrollTop

Related