1. 웹개발/1_1_8 Error Handling
Objects are not valid as a React child 해결 방법
코딩병원
2021. 12. 15. 12:38
이번 글에서는 Objects are not valid as a React child (found: object with keys {키1, 키2}). If you meant to render a collection of children, use an array instead. 에러 해결 방법에 대하여 알아보겠습니다.
Objects are not valid as a React child (found: object with keys {키1, 키2}). If you meant to render a collection of children, use an array instead.
[에러가 발생한 코드]
App.js
import './App.css';
import TestComponent from './Component/TestComponent'
function App() {
return (
<div>
<TestComponent Json={{key1:"코딩병원", key2:"119"}}/>
</div>
);
}
export default App;
TestComponent.js
import React, { Component } from 'react';
class TestComponent extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
let {Json} = this.props // key1: "코딩병원", key2: 119
return(
<div>
<p>{Json}</p>
</div>
);
}
}
export default TestComponent;
[에러 원인]
상위 컴포넌트 App.js가 TestComponent.js에 Object 타입으로 {key1: "코딩병원", key2: 119}의 데이터를 보내주고 있습니다. debugger로 데이터를 확인해보니 TestComponent에서도 {Json}에 데이터가 잘 들어와있습니다. 근데 이 객체를 그대로 렌더링하려고 하자 에러가 발생하였습니다.
[해결 방법]
Object 타입을 렌더링할 때는 오브젝트 타입을 지켜야 합니다. JSON.stringify()도 사용이 가능하겠고 여러가지 방법이 있을 것 같습니다. 따라서, 단순히 JSX 문법에 Object만 주지 말고 정확하게 명시해주시면 됩니다.
import React, { Component } from 'react';
class TestComponent extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
let {Json} = this.props // key1: "코딩병원", key2: 119
return(
<div>
<p>{Json.key1}</p> // 코딩병원
<p>{Json.key2}</p> // 119
<p>{JSON.stringfy(Json}</p> // {"key1":"코딩병원","key2":"119"}
</div>
);
}
}
export default TestComponent;