Reputation: 49
React is able to print any primitive values and react elements with JSX but if it encounters any object in JSX then it throws an error as "Objects are not valid as react children".
Please help me understand this and get the reason behind it.
Upvotes: 2
Views: 593
Reputation: 49
I have posted the same question to Dan Abramov in Twitter. Here is his reply to my query.
Initially I had this in my mind and from his reply it was clear now. Ask yourself the following question(s) to answer it yourself.
Well, it's really not clear on how to represent an object on the UI. After all, what we see on the page is mostly string content inside some html tag. So, react simply throws an error without proactively converting object to it's toString() or JSON representation and then showing it on the UI.
So, we as a developer should take out the relevant primitive information from that object and render in our components.
Addition on using function inside JSX expression: {() => console.log("I am arror function")}
React smartly warns us without throwing error and it is self explanatory.
Upvotes: 0
Reputation: 53884
You have a JSX in Depth section in React docs.
What are valid children in React and why?
Since JSX is synthetic sugar for React.createElement
, this function defines React element:
The type argument can be either a tag name string (such as 'div' or 'span'), a React component type (a class or a function), or a React fragment type ...
React.createElement(type, [props], [...children]);
React.createElement
React.createElement(React.Fragment,...)
.Why objects are not valid as react children?
// Objects are not valid as react children
<>
{ a:42 }
</>
Because objects are not in type definition of React.createElement
.
Upvotes: 1
Reputation: 11
<p>{children.someText}</p>
, but when you use an object for an element <p>{{ someText: 'hey' }}</p>
, React doesn't know how to parse it.Upvotes: 1