I got the same error today but with a different scenario as compared to the scenario posted in this question. Hope the solution to below scenario helps someone.
The render
function below is sufficient to understand my scenario and solution:
render() {
let orderDetails = null;
if(this.props.loading){
orderDetails = <Spinner />;
}
if(this.props.orders.length == 0){
orderDetails = null;
}
orderDetails = (
<div>
{
this.props.orders.map(order => (
<Order
key={order.id}
ingredient={order.ingredients}
price={order.price} />
))
}
</div>
);
return orderDetails;
}
In above code snippet : If return orderDetails
is sent as return {orderDetails}
then the error posted in this question pops up despite the value of 'orderDetails' (value as <Spinner/>
or null
or JSX related to <Order />
component).
Error description : react-dom.development.js:57 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {orderDetails}). If you meant to render a collection of children, use an array instead.
We cannot return a JavaScript object from a return call inside the render() method. The reason being React expects a component or some JSX or null to render in the UI and not some JavaScript object that I am trying to render when I use return {orderDetails}
and hence get the error as above.