Search code examples
reactjsnext.jsscroll

how to working go to scroll top with owerflow-y-auto ? (in Nextjs)


my div is overflow-y-auto. scrooltotop not working.

  const scrollToTop = () => {
          window.scrollTo({
            top: 0,
            behavior: "smooth",
          });
      };
      <div className="sticky z-30 top-0 h-screen overflow-y-auto inset-0 w-full bg-slate-100">
            <article className="prose px-5 py-2 my-4 bg-white rounded-md min-h-screen">
              <MDXProvider>
                <Post />
              </MDXProvider>
            </article>
            <button type="button" className="text-sky-900 fixed right-10 bottom-10 p-1" onClick={()=>scrolltoTop}>
            top
          </button>
          </div>

I also tried it as a divi reference, it still didn't work.

  const scrollable = useRef<HTMLDivElement>(null);
      <div className="sticky z-30 top-0 h-screen overflow-y-auto inset-0 w-full bg-slate-100" id="myElement" ref={scrollable}>

how can i get to the top in such a situation?


Solution

  • now working

     const scrollable = React.useRef() as React.MutableRefObject;
    
    
    const handleScrollTo = () => { scrollable.current.scrollTo({top:0, behavior: "smooth"}); };