React Native
React native에서 무한스크롤 구현하기 (FlatList 사용)
citron031
2022. 10. 27. 12:45
- FlatList는 ScrollView처럼 많은 양의 데이터를 처리할 수 있게 해준다.
- react에서 map을 쓰는 것 처럼 FlatList를 사용할 수 있고, 추가적으로 다양한 기능을 제공받을 수 있다.
- FlatList에서 필수적으로 필요한 props는 renderItem와 data다.
- 또한 map의 key를 설정해주는 것처럼 FlatList에서는 keyExtractor로 key를 설정해준다.
- onEndReached를 통해서 리스트에 끝에 도달했을 때 실행될 함수를 설정할 수 있고, 이를 통해서 무한스크롤을 구현할 수 있다.
- 스크롤 뷰가 리스트의 맨 끝에 도착하면 새로 다음 페이지의 데이터를 불러오는 함수를 실행시켜 무한스크롤을 구현한다.
- onEndReachedThreshold를 통해 마지막 컨텐츠의 어느정도 위치에 도달했을 때 onEndReached 함수를 호출할지 설정할 수 있다.
- ListFooterComponent를 사용하면 리스트의 맨 끝인 Footer에 노출되는 컴포넌트를 설정할 수 있다.
- refreshing과 onRefresh을 설정하면 화면을 위로 당겼을 때, 새로고침 기능을 구현할 수 있다.
- onRefresh에 새로고침 시 어떤 이벤트가 일어날지 함수를 연결한다.
예제 코드
import React, { useState } from "react";
import { FlatList, View, Text } from "react-native";
import styled from "styled-components/native";
const initData = [{
title: "title",
content: "content",
id: 1
}, {
title: "title",
content: "content",
id: 2
}, {
title: "title",
content: "content",
id: 3
}, {
title: "title",
content: "content",
id: 4
}, {
title: "title",
content: "content",
id: 5
}, {
title: "title",
content: "content",
id: 6
}, {
title: "title",
content: "content",
id: 7
}, {
title: "title",
content: "content",
id: 8
}, {
title: "title",
content: "content",
id: 9
}, {
title: "title",
content: "content",
id: 10
}]
const InfinityList = () => {
const [dummyData, setDummyData] = useState(initData);
const [isLoading, setIsLoading] = useState(false);
const onEndReached = () => {
if(!isLoading) {
setIsLoading(true);
setTimeout(() => {
setDummyData((prev) =>
[...prev, {
id: prev[prev.length - 1].id + 1,
content: "new content",
title: "new title"}]
);
setIsLoading(false);
}, 3000);
}
}
return (
<FlatList
data={dummyData}
renderItem={renderItem}
keyExtractor={(item) => item.id}
onEndReached={onEndReached}
onEndReachedThreshold={0.8}
ListFooterComponent={
isLoading &&
<LoadingText>loading...</LoadingText>
}
refreshing={isLoading}
onRefresh={() => console.log(isLoading)}
/>
)
}
const renderItem = ({ item }) => {
return (
<OuterView>
<View>
<Text>id: {item.id}</Text>
</View>
<View>
<Text>title: {item.title}</Text>
</View>
<View>
<Text>content: {item.content}</Text>
</View>
</OuterView>
);
};
const OuterView = styled.View`
margin: 20px;
`
const LoadingText = styled.Text`
text-align: center;
color: red;
font-weight: 700;
margin: 15px;
padding: 15px;
border-width: 1px;
`
export default InfinityList;
참고 자료 : https://reactnative.dev/docs/flatlist
FlatList · React Native
A performant interface for rendering basic, flat lists, supporting the most handy features:
reactnative.dev