React-Native FlatList 특정 데이터 선택하기

dev.horang🐯·2023년 3월 10일
0

React-Native

목록 보기
11/15

FlatList 를 사용한 리스트에서 특정 값을 선택하고 선택 됨을 표시되게 하는 부분이 필요했고 이렇게 코드를 사용했다.


 const [selectedId, setSelectedId] = useState(null);

  const renderItem = ({ item }) => {
    const borderColor = item.id === selectedId
      ? '#2E4052' : '#FFFFFF'

    const borderWidth = item.id === selectedId
      ? 2: 0;

    return (
      <MapView
        item={item}
        onPress={() => {
          setSelectedId(item.id)
        }}
        borderColor={{ borderColor }}
        borderWidth={{ borderWidth }}
      />
    );
  };

 const MapView = ({ item, onPress, borderColor, borderWidth }) => {

    return (
      <Pressable
        style={[styles.workout, borderColor, borderWidth]}
        onPress={onPress}
      >
        <View style={styles.pic}>
          <Image source={assets.noVideo} />
        </View>
        <View style={{ justifyContent: 'center', width: '58%' }}>
          <Text
            style={styles.workoutName}
            ellipsizeMode="tail"
            numberOfLines={3}
          >
            {item.title}
          </Text>
        </View>
      </Pressable>
    );
  };

return(
<FlatList
          data={myList}
          renderItem={renderItem}
          keyExtractor={(item) => item.id}
          extraData={selectedId}
        />
)

결과적으로 클릭시 setSelectedId로 클릭한 항목의 아이디를 담고 그때 css값을 다르게 넘겨서 클릭시 해당 항목이 하이라이트 되게 된 것이다! 호예!!

profile
좋아하는걸 배우는건 신나🎵

0개의 댓글