[React] Objects are not valid as a React Child

Jane·2023년 5월 15일
0

Error Log

목록 보기
4/6
post-thumbnail

게시판, 상세페이지를 구현하면서 겪었던 에러 회고 (1)

prop으로 받아온 json 데이터들을
자식 컴포넌트에서 map을 사용하여

return(
<div>
      {props.Comments.map((comment, i) => (
          <p>작성자: {comment.User.nickname}</p>
        <p>
          댓글내용:{comment.content}
        </p>
        ))}
    </div>
    )

위와 같은 방식으로 화면에 띄우려 했을 때 발생했던 에러이다.

분명 Array 형태이지만 typeof를 사용하여 자료형을 콘솔에 찍으면
object라는 값이 출력되면서

Uncaught Error: Objects are not valid as a React child
(found: object with keys {id, Follow}).
If you meant to render a collection of children, use an array instead.

해당 코드 실행 시 이러한 오류가 계속 발생하였다.

The "objects are not valid as a react child" error is thrown when you try to pass an object directly to a React component as a prop or child. To fix this error, you need to convert the array, for example, into a valid React child by iterating over its values and rendering them as React elements. This will allow React to render the object as part of the component's output, without throwing an error.

참고사이트의 설명을 참조하여
map을 자식 컴포넌트에서 사용하는 것이 아니라

// 부모 컴포넌트 부분
<S.CommentList>
        {post.Comments.map((comment, i) => (
          <Comment
            key={i}
            comment={comment}
          />
        ))}
      </S.CommentList>
// 자식 컴포넌트 부분
function Comment(props) {
  const { comment } = props;
  const { User, content, myComment } = comment;

  return (
    <div>
      <S.CommentItem>
        <p>작성자: {User.nickname}</p>
        <p>
          댓글내용:{" "}
          {isEditMode ? <input onChange={handleInputVal}></input> : content}
        </p>
        <button onClick={handleIsEditMode}>수정</button>
        {myComment && <button onClick={onDelete}>삭제</button>}
      </S.CommentItem>
    </div>
  );
}

부모 컴포넌트에서 map을 사용하여 개별 comment를 전달해주었더니 해결되었다.

Reference
참고사이트

profile
An investment in knowledge pays the best interest🙃

0개의 댓글