The “Objects are not valid as a React child” error is thrown when you try to pass an object directly to a React component as a prop or child. This is because React expects children to be either individual elements or arrays of elements. Objects are not valid children because they cannot be rendered directly by React.
What are the causes of the error?
There are a few common causes of this error, including:
- Passing an object as a prop to a React component. For example, the following code will throw the error:
const MyComponent = () => {
return <SomeOtherComponent prop={{}} />;
};
- Passing an object as a child to a React component. For example, the following code will also throw the error:
const MyComponent = () => {
return (
<div>
{[{}]}
</div>
);
};
- Using a function as a child to a React component. Functions are not valid children because they cannot be rendered directly by React. For example, the following code will also throw the error:
const MyComponent = () => {
return (
<div>
{() => {}}
</div>
);
};
How to fix the error
To fix the error, you need to convert the object into a valid React child. This can be done in a few different ways:
- Convert the object to an array of elements. For example, the following code will fix the error:
const MyComponent = () => {
return (
<div>
{[{ key: "value" }]}
</div>
);
};
- Use a map function to iterate over the object and render each value as a React element. For example, the following code will also fix the error:
const MyComponent = () => {
const object = { key: "value" };
return (
<div>
{Object.entries(object).map(([key, value]) => (
<span key={key}>{value}</span>
))}
</div>
);
};
- Use a higher-order component to wrap the object and render it as a valid React child. There are a number of higher-order components available that can be used to fix this error. For example, the following code uses the
react-children
library to fix the error:
import React from "react";
import { Children } from "react-children";
const MyComponent = () => {
const object = { key: "value" };
return (
<div>
{Children.map(object, (value) => (
<span key={value}>{value}</span>
))}
</div>
);
};
Conclusion
The “Objects are not valid as a React child” error can be a frustrating one to debug. However, by following the tips in this article, you should be able to fix the error and get your React code working again.
I hope this helps! Let me know if you have any other questions.