Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects are not valid as a React child (found: object with keys {children}): ReactJS

Tags:

reactjs

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?

like image 686
Avery235 Avatar asked Oct 29 '17 16:10

Avery235


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 map an object in React?

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.

How do you render an array of objects in React?

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.


1 Answers

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'/>
like image 121
Mayank Shukla Avatar answered Oct 10 '22 02:10

Mayank Shukla