Reputation: 935
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.
Upvotes: 9
Views: 3592
Reputation: 1
export const waitForElement = <K extends keyof HTMLElementTagNameMap>(
sel: K,
cb: (el: HTMLElementTagNameMap[K]) => void
) => {
const el = document.querySelector(sel)
if (!el || !el.offsetHeight) {
requestAnimationFrame(() => waitForElement(sel, cb))
} else {
cb(el)
}
}
//Use this function to scroll top.
export function scrollTop() {
waitForElement("ion-content", (contentEl) => {
if (contentEl) {
contentEl.scrollToTop()
}
})
}
Upvotes: 0
Reputation: 837
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>
.....
);
};
Upvotes: 15