목차

원인

해결

1. 직렬화하여 출력하기

2. map을 사용하여 올바르게 랜더링하기

3. null 체킹하기

4. 올바른 값 출력하고 있는지 체크하기

결론

태그

#NEXTJS

#NEXT

#REACT

#ERROR

Error: Objects are not valid as a React child

2024년 1월 19일 14:46

58-thumbnail-image

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

원인

에러가 났었던 코드입니다.

export default async function BlogDetail({
  params: { id },
}: {
	params: { id: number }
}) {
	const post: Post = await fetchBlog(id);

	return <>
		<div className={styles.postWrapper}>
			<div>
				{post}
			</div>
		</div>
	</>;
}

해결

잘 보시면 post 객체 전체를 출력하려고 시도했습니다!

이 오류 메시지는 구성 요소가 유효한 React 하위 요소(문자열, 숫자 또는 React 요소이지만 배열이나 개체는 아님) 대신 유효하지 않은 개체를 수신했음을 의미합니다.

이 오류의 주요 원인은 잘못된 데이터 유형직렬화할 수 없는 데이터를 하위 항목으로 전달하는 것입니다.

아래는 위 에러에서 사용할 수 있는 해결 방법들입니다.

1. 직렬화하여 출력하기

export default function App() {
  const message = { text: "Hello world!" };
  return (
    <div>
      {JSON.stringify(message)}
    </div>
  );
}

이 예에서는 message 객체를 하위 요소로 전달하기 전에 JSON.stringify() 메서드를 사용하여 문자열로 변환합니다. 이렇게 하면 "Objects Are Not Valid as a React Child" 오류가 발생하는 것을 방지할 수 있습니다.

2. map을 사용하여 올바르게 랜더링하기

export default function App() {
  const students = [
		{ name: 'John Doe', age: 12 },
		{ name: 'Jane Doe', age: 14 },
	];
	return (
		<>
		{students.map((student, index) => (
			<div key={index}>
				<span>{student.name}</span>
				<span>{student.age}</span>
      </div>
		))}
		</>
  );
}

이 코드에서는 map() 메서드를 사용하여 students 배열을 반복하고 각 요소를 학생의 이름과 나이가 포함된 div로 변환합니다. 또한 렌더링 성능을 최적화하기 위해 각 하위 요소에 key prop을 추가합니다.

3. null 체킹하기

function App() {
  const message = { text: "Hello world!" };
  return (
    <div>
      {typeof message === 'string' ? message : null}
    </div>
	);
}

이 예에서는 조건부 렌더링을 사용하여 메시지가 문자열인 경우에만 렌더링합니다. 이렇게 하면 "Objects Are Not Valid as a React Child" 오류가 발생하는 것을 방지할 수 있습니다.

4. 올바른 값 출력하고 있는지 체크하기

저같은 경우는, 출력해야할 정상적인 값을 입력하지 않았기 때문에 프로퍼티를 정상적으로 호출하여 해결하였습니다.

export default async function BlogDetail({
  params: { id },
}: {
	params: { id: number }
}) {
	const post: Post = await fetchBlog(id);

	return <>
		<div className={styles.postWrapper}>
			<div>
				{post.content}
			</div>
		</div>
	</>;
}

결론

  • 정신 차리고 출력할 때 잘 확인하고 하자.
  • 오타 먼저 확인하자