[React.js] unique "key" prop 에러 발생 시 map() 에 index 값 넣는 방법

Yuri Lee·2021년 8월 12일
0

배경

  • react 에서 다음의 에러를 마주했다.

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

원인

javascript map 을 통해 배열의 값을 돌며 리스트를 출력하고 있었다. 리스트아이템 출력 시 key prop 을 넣어줘야 하는데, data 안에 key 로 쓰일만한 요소가 없었다. 😯 (이를테면 id 값과 같은..)

Array.prototype.map()

arr.map(callback(currentValue[, index[, array]])[, thisArg])

mdn 에 가서 map 에 대해 확인하니, index 값이 있네? 이걸 활용해보기로 결정했다.

해결 방법

const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return currElement; //equivalent to list[index]
});

다음의 방법을 활용하니 더 이상 워닝 메시지가 발생하지 않았다. ☺☺


https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://stackoverflow.com/questions/38364400/index-inside-map-function

profile
Step by step goes a long way ✨

0개의 댓글