const Label = children => (
<div className="label">{children}</div>
);
<Label>some text</Label>
This gives an error:
Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children, use an array instead.
What's the right way to do it?
The React. js error "Objects are not valid as a React child" occurs when we try to directly render an object or an array in our JSX code. To solve the error, use the map() method to render arrays or access properties on the object in your JSX code.
To map through an object's value in React:Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.
To render an array of objects in react with JSX we need to use Array. map() to transform the object into something react can make use of because you cannot directly render an object into React. Instead, by using Array.
Reason for Objects are not valid as a React child?
Because here:
const Label = children => (
<div className="label">{children}</div>
);
Children is just the argument name, it will have the values of props, and it will be an object, like this:
props = {
children: .....
}
Possible Solutions:
Use destructuring and take out the children from props objects, it will work. Like this:
const Label = ( {children} ) => (
<div className="label">{children}</div>
);
Or use children.children
(actually it will be props.children):
const Label = children => (
<div className="label">{children.children}</div>
);
Check working example (check the console log values you will get the better idea):
const Label1 = (children) => {
console.log(children);
return <div className="label">{children.children}</div>
};
const Label2 = ({children}) => {
console.log(children);
return <div className="label">{children}</div>
};
ReactDOM.render(<div>
<Label1>ABC</Label1>
<Label2>ABC</Label2>
</div>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With