In React Native, you can load data into a list using components like FlatList or SectionList. Here’s a simple approach using FlatList. The sample implementation is as given below.
import React, { useState, useEffect } from 'react';
import { FlatList, Text, View, ActivityIndicator } from 'react-native';
const DataList = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
try {
// Replace with your API endpoint
const response = await fetch('https://api.example.com/data');
const json = await response.json();
setData(json);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
const renderItem = ({ item }) => (
<View style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: '#ccc' }}>
<Text>{item.title}</Text>
<Text>{item.description}</Text>
</View>
);
return (
<View style={{ flex: 1 }}>
{loading ? (
<ActivityIndicator size="large" color="#0000ff" />
) : (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={item => item.id.toString()}
/>
)}
</View>
);
};
export default DataList;
Let me break down how this React Native code works for loading data into a list:
- Initial Setup:
- We import essential components from React and React Native.
- We set up two state variables:
data
(empty array) to store our fetched items andloading
(true) to track the loading state.
2. useEffect Hook:
- The
useEffect
hook with an empty dependency array[]
ensures thatfetchData()
runs once when the component mounts. - This is where we trigger our data loading process.
3. fetchData Function:
- This async function handles the API call.
- It uses JavaScript’s built-in
fetch
API to request data from a server. - The
try/catch/finally
structure provides error handling and ensures loading state is updated regardless of success or failure. - When data is successfully received, it’s parsed from JSON and stored in the
data
state withsetData()
.
4. renderItem Function:
- This defines how each item in the list should be displayed.
- It receives an object with an
item
property containing the current data item. - Returns a simple View with two Text components displaying item properties.
5. Component Return:
- Uses conditional rendering based on the
loading
state. - While loading, shows a spinning ActivityIndicator.
- When loading is complete, renders the FlatList component.
6. FlatList Configuration:
data
: The array of items from our state.renderItem
: The function that defines how each item looks.keyExtractor
: Extracts a unique key for each item, which helps React optimize rendering.
The key advantage of FlatList is that it’s optimized for performance – it only renders items that are currently visible on screen, making it efficient for long lists of data.