FlatList는 배열로 된 데이터를 이용해서 반복적인 뷰 아이템을 만들 수 있다.
FlatList를 통해 원하는 아이템이 있는 곳으로 스크롤이 필요할 때 scrollToIndex를 사용하여 스크롤을 해준다.
const flatListRef = useRef<FlatList>(null);
const [isOpen, setIsOpen] = useState<boolean>(false);
const toggle = () => setIsOpen(prev => !prev);
const handleOnPress = (index: number) => {
toggle();
setTimeout(() => {
flatListRef.current?.scrollToIndex({
index,
animated: true,
});
}, 100);
}
const renderItem = ({ item, index }) => (
<Style.Container
onPress={() => {handleOnPress(index)}}
<Style.TitleArea>
<Font.Title>{`[${item.catagory}] ${item.title}`}</Font.Title>
</Style.TitleArea>
<FastImage
source={isOpen ? OpenIcon : CloseIcon}
style={{
width: 12,
height: 8,
}}
/>
</Style.Container>
}
<FlatList
keyExtractor={item => item.key}
ref={flatListRef}
data={data}
renderItem={renderItem}
/>
해당 container를 클릭을 때 toggle이 되면서
100밀리(0.1초) 후에 flatListRef.current?.scrollToIndex를 호출을 한다.
이때, flatListRef.current.scrollToIndex({animated: true, index}); 이런식으로 index의 값에 이동시키고 싶은 아이템 번호를 넣어주면 된다!