본문 바로가기
카테고리 없음

[ReactNative] Warning: Each child in a list should have a unique "key" prop 경고창

by 너구리새우깡 2022. 4. 19.

ScrollVoew에 임시데이터를 넣어서 리스트뷰를 만들었는데

Warning: Each child in a list should have a unique "key" prop

라는 노란 경고창이 떴다. 

 

내가 스크롤뷰 안에 작성한 예제 item뷰는 다음과 같다.

const categoryItem = () => {
    const result = [];
    for (let i = 0; i < 10; i++) {
        result.push(
            <Pressable
                style={{
                    width: 100,
                    height: 80,
                    alignItems: 'center',
                    backgroundColor: Colors.greenyBlue,
                    margin: 5,
                    borderRadius: 10,
                    paddingVertical: 6,
                }}
                onPress={() => sliderTouch(i, '카테고리')}>
                <LangText
                    ko={[f.b13, { color: Colors.white }]}
                    style={{
                        backgroundColor: Colors.grey,
                    }}>
                    카테고리{i + 1}
                </LangText>
                <Image
                    style={{ position: 'absolute', marginTop: 26 }}
                    source={require('../../../../assets/images/sample/icons8-home.png')}
                />
            </Pressable>,
        );
    }
    return result;
};

 

해결

찾아보니 React는 key prop을 사용하여 구성요소와 DOM요소 간의 관계를 만들기 때문에, 

배열로 UI목록을 만들때 각 하위 children 컴포넌트에 key prop을 추가해줘야한다고 한다. 

 

결론

<Pressable>안에 item 데이터를 넣어주니 경고창이 사라졌다. 

 

yeah ~ 

 

 

참고사이트:

https://sentry.io/answers/unique-key-prop/