'window.scrollTo() is not functioning properly in react ionic

I have a listing page in my application. When the user searches for any word the list will be displayed accordingly! To achieve this I am using two components(Let's say search and listing). When the search result is found the array will be passed to another component (i.e. listing component).

Now, the scroll-to-top button is not on the listing component. It is on the searching component. I am calling window.scrollTo(0,0) But nothing is working!

Here is the code:

const scrollToTop = () => {
        window.scrollTo(0,0)
    }

return (
     <div className={`!overflow-y-auto container bg-satin-3 rounded-lg pt-3 pb-6 md:px-3 h-fit xl:pb-3 2xl:pb-2 lg:pb-4`} >
      <ComponentCalled to display the listing />
      <IonButton
         onClick={() => scrollToTop()}
         className="float-right"
       >
       Scroll to Top
       </IonButton>
)


Solution 1:[1]

I have reuse your code and In my case it's working perfectly as shown below:

scrollToTop = () => { window.scrollTo(0,0); };

return (
  <div className="css" >
    <p>TOP</p>
    <ComponentCalled name="! I'm working"/>
  
  <button
     onClick={() => this.scrollToTop()}
     className="float-right"
   >
   Scroll to Top
   </button>
   </div>
);

https://stackblitz.com/edit/react-ts-vk1fle?file=index.tsx

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manoj Kumar