Home > Net >  Scroll to top when using pagination in React
Scroll to top when using pagination in React

Time:01-17

I am loading data card and when I press pagination buttons, the data changes but screen remains in the same place. How do I scroll to top when button is pressed? The application is a SPA so maybe that is causing the issue?

CodePudding user response:

Since the application is a SPA, the page is likely not reloading when you move to next page. You'll have to manually scroll to the top of the component.

To do that, add a ref to the wrapper of the content that you want to scroll to the top of:

const wrapperRef = useRef(null);

// ... blablabla component stuff

return {
  <div ref={wrapperRef}></div>
}

Then just make sure you next page button handler has access to the ref:

const handleNextPageButtonClick = async () => {
  await getNextPage();
  wrapperRef.current.scrollIntoView();
}

CodePudding user response:

Another way you could do it is with a useEffect in the component gets the new data on page change

    useEffect(()=>{
        window.scrollTo({top: 0});
    },[])
  •  Tags:  
  • Related