Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding in a scroll button with Ionic React

I'm trying to add in a button which scrolls to the top of the page, using Ionic React. This is part of my code so far -

...
function scrollToTop() {
    return document.getElementById("page")!.scrollTop;
}

const Home: React.FC = () => {
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
            <IonButtons slot="start">
                <IonMenuButton />
            </IonButtons>
            <IonTitle slot="end">Ionic Template - JB</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent id={"page"}>
        <IonCard  className="welcomeImage">
            <img src="/assets/welcomeBacking.jpg" alt=""/>
            <IonCardHeader>
                <IonCardTitle>Welcome!</IonCardTitle>
                <IonCardSubtitle>To this Ionic Template</IonCardSubtitle>
            </IonCardHeader>
            <IonCardContent>
                Lorem ipsum........
            </IonCardContent>
        </IonCard>
        {/*Checklist*/}
        <IonList>
            {form.map(({val, isChecked, isDisabled}) => (
                <IonItem key={val}>
                    <IonLabel>{val}</IonLabel>
                    <IonCheckbox slot={"start"} value={val} checked={isChecked} disabled={isDisabled} />
                </IonItem>
                ))}
        </IonList>
          <IonButton onClick={scrollToTop}>Scroll to top</IonButton>
      </IonContent>
    </IonPage>
  );
};

The scrollToTop function should scroll to the to the top of the element with id 'page' but tis doesn't. I don't get any errors when clicking the button, instead nothing at all happens.

I know this is a trivial thing to implement in Angular but I'm having trouble using React for this. Any help would be great thanks.

like image 602
James Brightman Avatar asked Nov 06 '19 12:11

James Brightman


1 Answers

You can do this with scrollToTop method of IonContent, but you have to enable scrollEvents first. In ionic react, the methods can be accessed using refs. Doesn't look much reacty but at least this works for now.

........    
import React, {useRef} from 'react';

const Home: React.FC = (props) => {
    const contentRef = useRef<HTMLIonContentElement | null>(null);
    const scrollToTop= () => {
        contentRef.current && contentRef.current.scrollToTop();
    };
    return (
        .....
        <IonContent ref={contentRef} scrollEvents={true}>
            ................
            <IonButton onClick={()=>scrollToTop()}>Scroll to top</IonButton>
        </IonContent>
        .....
    );
};
like image 160
Mark Avatar answered Nov 16 '22 06:11

Mark