Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 48979

How to use IonContent scrollToTop in functional component?

$
0
0

I want to add a button that users can click to scroll to top on my Ionic React v5 app.

I see that IonContent has a scrollToTop method but the example in the docs is for a class component, not a functional component.

Could someone please show me how to use scrollToTop with a functional component?

myPage.tsx

const TestPage: React.VFC = () => {

    return (
      <IonPage>
        <IonContent
          scrollEvents
        >
          <MainText
          />
          <IonButton onClick={() => scrollToTop()}>Scroll to top</IonButton>
        </IonContent>
      </IonPage>

What I tried:

I originally wrote my own function:

export function scrollToPageTop(): void {
  console.log('scrollToTop initialized', body);
  if (body) {
    body.scrollToTop();
  }
}

This code works on iOS and Chrome desktop, but on Android, it would sometimes grab the wrong IonContent (it would try to scroll to an IonContent that was offscreen on a page still in memory instead of the onscreen IonContent).

I also tried several standard Javascript approaches for scrolling to top, but these didn’t work on Ionic.

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 48979

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>