본문 바로가기
React/Native

EXPO) FlashList로 다양한 크기의 이미지 보여주기

by 후르륵짭짭 2025. 2. 23.
728x90
반응형

어떤 유럽의 새벽 풍경

 

안녕하세요. 짭짭이 입니다.

이번에는 EXPO에서 FlatList가 아닌 FlashList로 다양한 크기의 이미지를 보여줄 수 있는것을 구현해봤습니다.

또한 일반적인 Image가 아닌 Image Caching을 지원하는 Expo-image 를 사용해서 이미지를 보여주는 것을 해봤습니다.

 

** 기본 컴포넌트 구조 **

	<View>
      <Categories handleChangeCategory={handleChangeCategory} activeCategory={activeCategory}/>
    </View>

    <View>
      <ImageGride images={images} />
    </View>

 

** FlatList를 활용한 Categories 컴포넌트 **

export function Categories({ activeCategory, handleChangeCategory }: { activeCategory: string , handleChangeCategory: (category: string | null) => void }) {
  return (
    <View>
        <Text>Categories</Text>
        <FlatList 
          horizontal={true}
          data={data.categories}
          renderItem={({ item, index }) => <CategoryItem handleChangeCategory={handleChangeCategory} isActive={activeCategory===item} item={item} index={index} />}
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={style.flatListContainer}
          keyExtractor={(item) => {return item}}
        />
    </View>
  );
}

https://reactnative.dev/docs/flatlist

 

FlatList · React Native

A performant interface for rendering basic, flat lists, supporting the most handy features:

reactnative.dev

기본적으로 FlatList는 KeyExtractor , contentContainerStyle, renderItem, data를 채워줘야합니다.

FlatList를 사용하면 ScrollView 기반의 리스트들을 쉽게 만들수 있습니다.

Swift에서 List랑 비슷한 것이죠.

 

** Flash List ** 

import { MasonryFlashList } from "@shopify/flash-list"
import { ImageCard } from './ImageCard';

export function ImageGride({images}:{images: ImageResponse[]}) {

 let columns = getColumnCount()

  return (
    <View style={style.constainer}>
        <Text>ImageGride</Text>
        <MasonryFlashList 
              data={images} 
              numColumns={columns}
              estimatedItemSize={200}
              contentContainerStyle={{padding: 10}}
              renderItem={({item,index})=> {
                return (
                    <ImageCard column={columns} item={item} index={index}/>
                )
              }}        
              />
    </View>
  );
}

https://shopify.github.io/flash-list/

 

FlashList - super fast list for react native

FlashList is a faster alternative to FlatList with a similar API. Migrate in a few seconds and get major performance boost.

shopify.github.io

일단 Shopify라는 나스닥에 상장되어 있는 회사가 ReactNative를 사용해서 좋은 성능의 FlatList를 만든거라 보시면 될 듯합니다.

일단 이렇게 성능이 더 좋다고 합니다. (앞으로의 미래를 위해 그냥 취미로 Expo를 하는 것이니 왜는 신경 안 쓰도록 하겠습니다 ^^)

일단 FlatList랑 달리 Web에서도 좋은 성능을 보여주는 것을 확인 했습니다. (Expo의 가장 큰 장점이 WEB도 된다는것 같습니다.)

사용 방법은 비슷합니다. 

npx expo install @shopify/flash-list

FlatList는 기본설치 되어 있지만 Flash List는 위 명령어로 설치 해줘야합니다.

const MyList = () => {
  return (
    <FlashList
      data={DATA}
      renderItem={({ item }) => <Text>{item.title}</Text>}
      estimatedItemSize={200}
    />
  );
};

기본적으로 FlatList랑 비슷한데, 기본옵션이 EstimatedItemSize가 들어갑니다. 설명은 대략적인 사이즈를 알고 싶다는 것 같습니다.

그리고 장점이 다양한 Layout을 제공합니다.

저 같은 경우는 MasonryLayout으로 renderItem의 사이즈를 기반으로 사이즈가 다른 뷰를 보여주도록 되어 있습니다.

 

** Expo-Image ** 

import { Image } from 'expo-image';

export function ImageCard({item, index, column}: {item: ImageResponse, index: number, column: number}) {

    const blurhash =
  '|rF?hV%2WCj[ayj[a|j[az_NaeWBj@ayfRayfQfQM{M|azj[azf6fQfQfQIpWXofj[ayj[j[fQayWCoeoeaya}j[ayfQa{oLj?j[WVj[ayayj[fQoff7azayj[ayj[j[ayofayayayj[fQj[ayayj[ayfjj[j[ayjuayj[';

    function getImageHeight(): {height: number} {
        let {imageHeight: height, imageWidth: width} = item;
        return {height: getImageSize(height, width)};
    }

    function isLastInRow(): boolean {
        return (index + 1) % column === 0
    }

  return (
    <Pressable style={[style.imageWrapper, !isLastInRow() && style.spacing]}>
        <View>
            <Image
            style={[style.image, getImageHeight()]}
            source={item.webformatURL}
            placeholder={{ blurhash }}
            contentFit="cover"
            transition={1000}
            />
        </View>
    </Pressable>
  )
}

https://docs.expo.dev/versions/latest/sdk/image/

 

Image

A cross-platform and performant React component that loads and renders images.

docs.expo.dev

이번에는 Expo에서 제공하는 Image를 사용하였습니다.

일단 기본적으로 Cache 기능을 가지고 있어서 Image를 더욱 효율적으로 보여줄 수 있다고 합니다.

npx expo install expo-image

위 명령어로 Expo Image를 설치를 해줍니다.

그냥 Image랑 다른 점은 placeholder가 있고 이 placeholder는 이미지가 로딩 중일 때 블러 같은 효과를 줄 수 있었습니다.

그리고 Image에는 반드시 이미지의 Size를 넣어줘야합니다. 

따라서 아래와 같이 Item의 이미지의 높이를 지정해준걸 볼 수 있습니다.

style={[style.image, getImageHeight()]}
728x90
반응형

댓글