The error “Objects are not valid as a React child” or “Functions are not valid as a React child” is a console error. When this error occurs, your console will display the following error message 👇
Why this error occurs ?
The error “Objects are not valid as a React child” or “Functions are not valid as a React child” occurs in React when you try to directly render an object or a function as a child component in JSX code.
Here’s a simple example that describe error caused by an object:
const App = () => {
const student = {
name: "Prateek",
age: 20,
};
return (
<div>
// ⛔️ Objects are not valid as a React child.
{student}
</div>
);
};
export default App;
In the above code, we have a simple ‘App
‘ component that tries to render the ‘student’ object directly within the JSX code. However, this will result in an error because objects are not valid React children.
Here’s a simple example that describe error caused by a function:
const App = () => {
function hello() {
return 'Hello, World!';
}
return (
<div>
// ⛔️ Functions are not valid as a React child.
{hello}
</div>
);
}
In this case, the App
component tries to render the 'hello'
function directly within the JSX code, resulting in an error.
How to fix the error ?
1. To resolve the error caused by an object, we can extract the necessary data from the object and render it appropriately.
// const App = () => {
// const student = {
// name: "Prateek",
// age: 20,
// };
// return (
// <div>
{student.name}
{student.age}
// </div>
// );
// };
// export default App;
2. To resolve the error caused by a function, you need to call the function:
// const App = () => {
// function hello() {
// return 'Hello, World!';
// }
// return (
// <div>
{hello()}
// </div>
// );
// }
I hope this article helped you to solve the error you were facing 🙏
SEE ALSO – WHAT IS THE DIFFERENCE BETWEEN JS AND JSX ?