React Native로 캐러셀 만들기🪟

임덤덤·2023년 5월 31일
0

캐러셀 만들기

  • React Native에서 캐러셀 구현은 ScrollView, FlatList로 충분히 만들수있다고 한다!
    • 그래서 나는 FlatList를 적용해서 만들어보려고 한다

FlatList

우선 사용하기전에 이친구에 대해서 정리를 해보려한다

  • FlatList는 배열성 데이터가 들어왔을때 해당 배열을 정리정돈 하여 뿌려주는 역할을 가지고 있다 자세한건 공식문서를 참고하자

코드

  • 우선 내 프로젝트의 구조를 먼저 짚고 넘어가야할꺼같다
    • Review Box라는 컴포넌트가 있고 그안에 Carousel이 들어가있는 형태

ReviewBox.tsx

interface ReviewPropsType {
  userName: string;
  userImage: string;
  reviewImage: string[];
  reviewMainText: string;
}

export default function ReviewBox(props: ReviewPropsType) {
  const screenWidth = Math.round(Dimensions.get("window").width);
  return (
    <View style={styles.reviewBoxContainer}>
      <View style={styles.userInfoContainer}>
        {/* 5월 31일 2시 8분 User Icon 추후 데이터값 인입시 Image로 변경 예정 */}
        <UserIcon name="user-circle-o" size={40} />
        <CustomText
          children="유저이름입니다"
          fontWeight="bold"
          fontSize="20px"
          marginLft="12px"
          marginTop="2px"
        />
      </View>
      <View style={styles.reviewImageContainer}>
        <Carousel
          images={props.reviewImage}
          gap={15}
          offset={36}
          pageWidth={screenWidth - (15 + 36) * 2}
        />
      </View>
      <View>
        <CustomText children={`${props.reviewMainText}`} />
      </View>
    </View>
  );
}
  • 캐러셀에 전달해주는 Props는
    • images : 이미지배열
    • gap: 이미지의 양옆갭
    • offset: 이미지와 이미지 사이의 간격
    • pageWidth: 해당 Screen의 width

Carousel.tsx

interface CarouselProps {
  images: string[];
  gap: number;
  offset: number;
  pageWidth: number;
}

export default function Carousel(props: CarouselProps) {
  const renderItem = (item: string, index: number) => {
    return (
      <Image
        key={item}
        source={{ uri: item }}
        style={{
          width: props.pageWidth,
          marginHorizontal: props.gap / 2,
          marginLeft: 0,
          borderRadius: 5,
          marginRight: index === props.images.length - 1 ? 0 : 20,
        }}
      />
    );
  };

  return (
    <View style={styles.container}>
      {props.images.length === 1 ? (
        <Image source={{ uri: props.images[0] }} style={styles.image} />
      ) : (
        <FlatList
          automaticallyAdjustContentInsets={false}
          data={props.images}
          decelerationRate="fast"
          horizontal
          renderItem={(item) => renderItem(item.item, item.index)}
          showsHorizontalScrollIndicator={false}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    height: 210,
    width: "100%",
  },
  imageWrapper: {
    width: 230,
    height: 210,
  },
  image: { width: "100%", height: "100%", borderRadius: 5 },
});
profile
응애🐣 예비 개발자 입니다.

0개의 댓글