📱테스트 환경
"react": "18.3.0",
"react-dom": "18.3.0"
map 을 사용하다보면
Warning: Each child in a list should have a unique "key" prop.
이런 경고 에러메시지를 볼 수 있다.
해당 코드를 보면
<View style={styles.Container}>
{category &&
category[2] &&
category[2].map((v, i) => (
<>
<Pressable
key={i}
onPress={() =>
setSelected(prev => (prev === v.no ? null : v.no))
}>
<Text
fontSize={12}
color={selected === v.no ? root.neutral_90 : root.neutral_60}
fontWeight={selected === v.no ? 700 : 400}>
{v.name}
</Text>
</Pressable>
{i !== category[2].length - 1 && <View style={styles.Divider} />}
</>
))}
</View>
React Native 코드이긴한데 문법은 거의 동일하기 때문에
보는데 문제는 없을 것이다.
React Native 인데 왜 React 에다가 적었냐고 ?
해당 문법이 React 에서 지원해주기 때문이다.
<></> 여기서는 key 를 지정해줄 수 없기 때문에 에러가 발생하는것이다.
React 에서는 React.Fragment 가 있기 때문에 사용해주면 key 를 지정해주면서
에러를 해결해줄 수 있는데
<View style={styles.Container}>
{category &&
category[2] &&
category[2].map((v, i) => (
<Fragment key={i}>
<Pressable
onPress={() =>
setSelected(prev => (prev === v.no ? null : v.no))
}>
<Text
fontSize={12}
color={selected === v.no ? root.neutral_90 : root.neutral_60}
fontWeight={selected === v.no ? 700 : 400}>
{v.name}
</Text>
</Pressable>
{i !== category[2].length - 1 && <View style={styles.Divider} />}
</Fragment>
))}
</View>
이렇게 해주면 콘솔창에 에러문구없이 깔끔하게 사용할 수 있다 :)
지금까지 <></> 를 사용했는데 React 에서는 Fragment 가 있다고 하니
이거를 대신 사용해주는 습관을 길러봐야지 ㅎ
'Javascript > React' 카테고리의 다른 글
[React] Antd DatePicker 한글 패치 하는 방법 (0) | 2024.12.20 |
---|---|
[React] Drag&Drop 을 위한 React-complex-tree (0) | 2024.12.19 |
[React] JSX.Element 곧 사용할 수 없게 될 심볼이 사용되었습니다 (0) | 2024.11.28 |
[React] xlsx-js-style (1) | 2024.11.26 |
[React] Styled-Compoent (1) | 2024.11.15 |