logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • AI Interviewer
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Q: Write a code to create a FlatList with infinite scrolling?

author
Generated by
Nitish Kumar Singh

30/10/2024

React Native

Infinite scrolling is a popular user interface pattern that allows for continuous content loading as a user scrolls down a list. In React Native, we can achieve this with the FlatList component, which has built-in support for rendering large lists efficiently. Here's how you can create a FlatList with infinite scrolling.

Step 1: Basic Setup

First, ensure you have your React Native environment set up. Create a new React Native project if you haven't done so:

npx react-native init MyProject cd MyProject

Make sure to install any required dependencies. You will be using react-native and axios for making API calls.

npm install axios

Step 2: Setting Up Your Data Source

You will need a function to simulate fetching data. For this example, we'll be using an array of mock data. In a real-world scenario, this would typically be replaced by a network request to your API.

Sample Data Fetcher

Here’s a simple function that returns mock data:

function fetchMoreData(page) { return new Promise((resolve) => { setTimeout(() => { const data = Array.from({ length: 10 }, (_, i) => ({ id: `item-${i + 1 + page * 10}`, title: `Item ${i + 1 + page * 10}`, })); resolve(data); }, 1000); }); }

Step 3: Create the FlatList Component

You will now create a FlatList that uses this function to fetch and display data. We’ll also manage state for the data, loading status, and the current page.

Here is a detailed implementation:

import React, { useState, useEffect } from 'react'; import { FlatList, Text, View, ActivityIndicator } from 'react-native'; const InfiniteScrollExample = () => { const [data, setData] = useState([]); const [loading, setLoading] = useState(false); const [page, setPage] = useState(1); useEffect(() => { loadData(); }, []); const loadData = async () => { if (loading) return; // Prevent multiple calls setLoading(true); const newData = await fetchMoreData(page); setData(prevData => [...prevData, ...newData]); setLoading(false); }; const handleLoadMore = () => { setPage(prevPage => prevPage + 1); loadData(); }; const renderItem = ({ item }) => ( <View style={{ padding: 20, borderBottomWidth: 1, borderBottomColor: '#ccc' }}> <Text>{item.title}</Text> </View> ); return ( <FlatList data={data} renderItem={renderItem} keyExtractor={item => item.id} onEndReached={handleLoadMore} onEndReachedThreshold={0.1} // Threshold for when to call load more ListFooterComponent={loading ? <ActivityIndicator /> : null} // Show loading spinner at the bottom /> ); }; export default InfiniteScrollExample;

Explanation of the Code:

  1. State Management: We use useState to maintain the list of data, loading state, and the current page.

  2. Data Fetching: The loadData function handles fetching new data and appending it to the existing list. The function checks if data is already being loaded to prevent overlapping requests.

  3. FlatList Implementation:

    • The FlatList component takes data, renderItem, keyExtractor, onEndReached, and ListFooterComponent as props.
    • onEndReached triggers when the user scrolls to the end of the list, calling handleLoadMore to increment the page and fetch more data.
    • ListFooterComponent displays a loading spinner when data is being fetched.

This code example gives you a solid foundation for an infinite scrolling FlatList in your React Native application. Feel free to customize the data fetching logic or UI according to your requirements!

Popular Tags

React NativeFlatListInfinite Scrolling

Share now!

Related Questions

  • What are the common performance issues in React Native and how can they be resolved

    30/10/2024 | React Native

  • Explain the use of Context API for global state management in React Native

    30/10/2024 | React Native

  • How does the React Native bridge work with native modules

    30/10/2024 | React Native

  • How does React Native handle state management in large-scale applications

    30/10/2024 | React Native

  • Explain the difference between controlled and uncontrolled components in React Native

    30/10/2024 | React Native

  • Write a function to debounce a button click in React Native

    30/10/2024 | React Native

  • Explain the lifecycle of a React Native component

    30/10/2024 | React Native

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design