Infinite Scroll With Ionic + React

Are you new to Ionic?

Yes

No

Go to deckdeckgo.com/poll and use the code {0}
Awaiting votes

Before We Start

ionic start infiniteScroll tabs --type react

Getting Started

  • ​Implementation of the solution in the first tab (./src/pages/Tab1.tsx)
  • We are adding a stateful value for our items (using the useState React Hook) 
  • And another state to stop the scroller
import { IonContent, IonHeader, IonPage, IonTitle, IonCard, IonToolbar} from '@ionic/react'; import React, {useState} from 'react'; const Tab1: React.FC = () => { const [items, setItems] = useState<string[]>([]); const [disableInfiniteScroll, setDisableInfiniteScroll] = useState<boolean>(false); return ( <IonPage> <IonHeader> <IonToolbar> <IonTitle>Tab One</IonTitle> </IonToolbar> </IonHeader> <IonContent> {items.map((item: string, i: number) => { return <IonCard key={`${i}`}><img src={item}/> </IonCard> })} </IonContent> </IonPage> ); };

Fetch API

We are going to fetch dogs with the awesome  Dog API  🐶

* Free and Open Source
* No token
* Support CORS requests
async function fetchData() { const url: string = 'https://dog.ceo/api/breeds/image/random/10'; const res: Response = await fetch(url); res .json() .then(async (res) => { if (res && res.message && res.message.length > 0) { setItems([...items, ...res.message]); setDisableInfiniteScroll(res.message.length < 10); } else { setDisableInfiniteScroll(true); } }) .catch(err => console.error(err)); }

Loading Initial Data

import {useIonViewWillEnter} from '@ionic/react'; const Tab1: React.FC = () => { useIonViewWillEnter(async () => { await fetchData(); }); };

Infinite Scroll

  1. Add a new function to fetch data on pagination
  2. Import the infinite scroll component
  3. Use it 😁
<IonInfiniteScroll threshold="100px" disabled={disableInfiniteScroll} onIonInfinite={(e: CustomEvent<void>) => searchNext(e)}> <IonInfiniteScrollContent loadingText="Loading more good doggos..."> </IonInfiniteScrollContent> </IonInfiniteScroll> import {IonInfiniteScroll, IonInfiniteScrollContent} from '@ionic/react'; async function searchNext($event: CustomEvent<void>) { await fetchData(); ($event.target as HTMLIonInfiniteScrollElement).complete(); }

Altogether

git clone https://github.com/peterpeterparker/infiniteScroll

Author

David Dal Busco

Freelancer by day | Creator of DeckDeckGo by night