Janakiram Maddanala
Janakiram Maddanala

Reputation: 49

Why objects are not valid as react children? What are valid children in react and why?

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

Answers (3)

Janakiram Maddanala
Janakiram Maddanala

Reputation: 49

I have posted the same question to Dan Abramov in Twitter. Here is his reply to my query.

How do you want DOM to represent object?

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.

  1. What do you expect to see when you use an object as children?
  2. How should an object be shown by React or DOM? Should they just show [Object object] or JSON string of that object?

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.

enter image description here

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.

enter image description here

Upvotes: 0

Dennis Vash
Dennis Vash

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]);
  • Tag name string is an HTML element string representation.
  • React component is an object created by React.createElement
  • React fragment is a special type created by 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

Oleksandr Skorochenko
Oleksandr Skorochenko

Reputation: 11

  • Technically you can use objects as children only for components (but not for elements).
  • When you use objects as children for your own component where you can decide how to handle this object in the render <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.
  • So, React throws the error to notify you that you are doing something wrong.

Upvotes: 1

Related Questions