react-native의 내장 component로 Scroll을 가능하게 해주는 component이다.
View component는 해당 component의 제한된 높이를 초과하는 부분은 볼 수 없지만, ScrollView를 사용하면 초과하는 부분도 scroll을 하여 볼 수 있게된다.
<View style={styles.goalsContainer}>
{courseGoals.map((goal, index) => (
<View key={goal + index} style={styles.goalItem}>
<Text style={styles.goalText}>{goal}</Text>
</View>
))}
</View>
View로 구현되어있는 container를 ScrollView로 바꿔주기만 하면 된다.
하지만 View부분을 ScrollView로 바꾸는 작업만 진행 시 부모컴포넌트의 style에 따라 원치않는 모습으로 바뀔 가능성이 있기 때문에 새로운 View component로 감싸준 뒤, 변경해준다.
<View style={styles.goalsContainer}>
<ScrollView>
{courseGoals.map((goal, index) => (
<View key={goal + index} style={styles.goalItem}>
<Text style={styles.goalText}>{goal}</Text>
</View>
))}
</ScrollView>
</View>
ScrollView의 경우 map으로 불러올 수 있는 모든 list의 내용을 렌더링해오기 때문에 list의 내용이 많거나, 동적으로 추가될 수 있는 경우 잘 사용하지 않는다.
FlatList는 항목이 나타나려고 할 때 렌더링하고 화면 밖으로 스크롤되는 항목을 제거하여 메모리와 처리 시간을 절약한다.
따라서 항목이 동적으로 변할 수 있는 상황이나, 무한 스크롤 같은 경우에 유용하다.
<View style={styles.goalsContainer}>
<ScrollView>
{courseGoals.map((goal, index) => (
<View key={goal + index} style={styles.goalItem}>
<Text style={styles.goalText}>{goal}</Text>
</View>
))}
</ScrollView>
</View>
ScrollView부분을 FlatList로 바꿔주면된다.
<View style={styles.goalsContainer}>
<FlatList
data={courseGoals}
renderItem={(itemData) => (
<View style={styles.goalItem}>
<Text style={styles.goalText}>{itemData.item}</Text>
</View>
)}
/>
</View>
중요한 점은 FlatList같은 경우는 map을 사용하는것이 아닌 data, renderItem property를 사용한다.
data property에서 렌더링할 배열을 받아와주고 renderItem에서 렌더링해준다.
FlatList에서 key를 설정하는 방법에는 2가지 방법이 존재한다.
첫번째로 렌더링할 배열의 요소를 object로 설정하고 해당 object의 값으로 key를 주는 것이다.
예를들어 [ { text : 'hi', key : 1 }, { text : 'bye', key : 2 } ] 이런식으로 배열을 구성할 시 FlatList가 알아서 key property를 찾아서 사용하게된다.
두번째로는 keyExtractor property를 사용하는것이다.
이번에는 렌더링할 배열의 요소를 [ { text : 'hi', id : 1 }, { text : 'bye', id : 2 } ] 이렇게 구성했다고 해보자.
그 후 keyExtractor={ ( item ) => item.id } 를 작성 시 object의 id라는 property를 찾아 key로 사용을 하게된다.
<View style={styles.goalsContainer}>
<FlatList
data={courseGoals}
renderItem={(itemData) => (
<View style={styles.goalItem}>
<Text style={styles.goalText}>{itemData.item.text}</Text>
</View>
)}
keyExtractor={(item)=>item.id}
/>
</View>
중요한 것은 두 경우 모두 key로 사용되어질 값은 유니크한 값이여야한다.