Warning: Encountered two children with the same key

henry·2024년 9월 25일

채팅 메세지를 입력하고, 보내기 버튼을 클릭하면 firebaseRealtime Database에 메세지 내용이 저장되는 기능.

보내기 버튼을 클릭하여 사용자가 입력한 메세지 내용 저장을 시도했지만, 오류 발생.

Warning: Encountered two children with the same key, `[object Object]`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
    at div
    at form
    at div
    at MessageForm (http://localhost:5173/src/pages/ChatPage/MainPanel/MessageForm.jsx?t=1727275964867:30:33)
    at div
    at MainPanel
    at div
    at div
    at ChatPage
    at RenderedRoute (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=067d8491:4092:5)
    at Routes (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=067d8491:4531:5)
    at App (http://localhost:5173/src/App.jsx:31:20)
    at Router (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=067d8491:4474:15)
    at BrowserRouter (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=067d8491:5219:5)
    at Provider (http://localhost:5173/node_modules/.vite/deps/react-redux.js?v=067d8491:1097:3)

"Encountered two children with the same key"라는 경고는 React에서 key 속성이 중복된 값을 가지는 경우에 발생하는 경고


소스 코드를 확인해보니 p태그의 key를 설정하는 부분이 잘못 작성되어 있는 것을 발견

{errors.map((errorMsg, i) => (
   <p key={{ i }} style={{ color: 'red' }}>
      {errorMsg}
   </p>
))}

key에는 고유한 값을 제공해야 하는데, { i }는 객체로 넘겨주기 때문에 문제가 발생한 것

key 속성에는 단순히 i를 넘기는 것으로 해결

수정된 소스 코드

{errors.map((errorMsg, i) => (
   <p key={i} style={{ color: 'red' }}>
      {errorMsg}
   </p>
))}

0개의 댓글