The error “Objects are not valid as a react child” occurs when you try to render a JavaScript object directly to the DOM, which React doesn’t support. For example, you can only render arrays, numbers, strings, booleans (which will not display anything but won’t throw an error), null, or other React elements to the DOM.
For example, if you try to render an object like this:
const obj = { name: 'Krunal Lathiya' };
return <div>{obj}</div>;
You’ll get the “Objects are not valid as a React child” error.
To fix this, you need to access the individual properties of the object:
const obj = { name: 'Krunal Lathiya' };
return <div>{obj.name}</div>;
If you’re dealing with an object with a lot of properties and you want to display all of them, you could map over the entries and display them:
const obj = { name: 'John Doe', age: 30, profession: 'Engineer' };
return (
<div>
{Object.entries(obj).map(([key, value], index) => (
<p key={index}>
{key}: {value}
</p>
))}
</div>
);
If you’re dealing with an array of objects, remember to use the .map() function and render individual properties of each object:
const people = [{ name: 'Krunal Lathiya' }, { name: 'Ankit Lathiya' }];
return (
<div>
{people.map((person, index) => (
<p key={index}>{person.name}</p>
))}
</div>
);
While it’s safe to use the index as a key when the list is static and won’t change, if you’re dealing with lists that can reorder, it’s better to use a unique identifier from each object as the key, like a person.id.
This way, you’re only rendering data types that React can handle. If you’re still facing issues, looking at the specific code causing the problem would be helpful.