Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

People also ask

How do you fix objects are not valid as a React child?

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.

How do you render collection of children in React?

If you meant to render a collection of children, use an array instead' Error. We can fix the 'Objects are not valid as a React child. If you meant to render a collection of children, use an array instead' error by rendering an array with the map method or render objects as strings or render the properties individually.

How do you render an array of objects in React?

To render an array of objects in React, we can use the array map method. const Item = (props) => { return <li>{props. message}</li>; }; const TodoList = () => { const todos = ["foo", "bar", "baz"]; return ( <ul> {todos. map((message) => ( <Item key={message} message={message} /> ))} </ul> ); };

What is a React child?

What are children? The children, in React, refer to the generic box whose contents are unknown until they're passed from the parent component. What does this mean? It simply means that the component will display whatever is included in between the opening and closing tags while invoking the component.


Your data homes is an array, so you would have to iterate over the array using Array.prototype.map() for it to work.

return (
    <div className="col">
      <h1>Mi Casa</h1>
      <p>This is my house y&apos;all!</p>
      {homes.map(home => <div>{home.name}</div>)}
    </div>
  );

I had a similar error while I was creating a custom modal.

const CustomModal = (visible, modalText, modalHeader) => {}

Problem was that I forgot that functional components can have only one prop passed to them, according to the REACT documentation:

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions. React docs

Therefore when we want to pass several variables we need to wrap them into an object or an Array and pass the pointer to that array or object. And destructure it on the component side before invoking the component. Alternatively we can use curly braces to indicate that we are sending an object with identical property names and variables that contain the value of those properties, like in the example here. And then define the function also to destructure upon arrival of the properties contained in the object.

const CustomModal = ({visible, modalText, modalHeader}) => {}

If you have multiple values to pass to the component, you should pass an object, thus curly brackets around its properties/variables (assuming they have the same name).


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 && 
                this.props.orders.length > 0 && 
                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 some JSX, false, null, undefined, true 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.

VALID :

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

INVALID :

<div>{orderDetails}</div> // This is WRONG, orderDetails is an object and NOT a valid return value that React expects.

Edit: I also got this error on my company's test server used by QA's for their testing. I pointed my local code to that test server and tested the scenario in which this error was reported by QA team and found NO ERROR in my local machine. I got surprised. I re-checked multiple number of times, re-checked the scenario with QA team and I was doing right but still I was not able to replicate the issue. I consulted my fellow devs but still were not able to figure out the root cause. So keeping with the information in the error message I started scanning all the code I had deployed in my last deployment commit ( to be more specific last 4-5 commits because I suspected it could be there from last few deployments but was caught in the current deployment), especially all the components I had developed and found that there was a component - inside which there was no specified condition being met so it was returning NOTHING from it. So see below sample pseudo code. I hope it helps.

render () {
return (
    {this.props.condition1 && (
       return some jsx 1
    )}

    {this.props.condition1 && (
       return some jsx 2
    )})
}

If you see in above pseudo code if condition1 and condition2 are not met then this component will render NOTHING from it and ideally a react component must return some JSX, false, null, undefined, true from it.


I hope it will help someone else.

This error seems to occur also when you UNintentionally send a complex object that includes for example Date to React child components.

Example of it is passing to child component new Date('....') as follows:

 const data = {name: 'ABC', startDate: new Date('2011-11-11')}
 ...
 <GenInfo params={data}/>

If you send it as value of a child component parameter you would be sending a complex Object and you may get the same error as stated above.

Check if you are passing something similar (that generates complex Object under the hood). Instead you can send that date as string value and do new Date(string_date) in child component.


Although not specific to the answer, this error mostly occurs when you mistakenly using a JavaScript expression inside a JavaScript context using {}

For example

let x=5;

export default function App(){ return( {x} ); };

Correct way to do this would be

let x=5;
export default function App(){ return( x ); };

Had the same issue, In my case I had 1. Parse the string into Json 2. Ensure that when I render my view does not try to display the whole object, but object.value

data = [
{
    "id": 1,
    "name": "Home Page",
    "info": "This little bit of info is being loaded from a Rails 
    API.",
    "created_at": "2018-09-18T16:39:22.184Z",
    "updated_at": "2018-09-18T16:39:22.184Z"
}];
var jsonData = JSON.parse(data)

Then my view

return (
<View style={styles.container}>
  <FlatList
    data={jsonData}
    renderItem={({ item }) => <Item title={item.name} />}
    keyExtractor={item => item.id}
  />
</View>);

Because I'm using an array, I used flat list to display, and ensured I work with object.value, not object otherwise you'll get the same issue