Mastery: Fixing "Objects are not valid as a React child" Error
In modern React development, seemingly small mistakes can lead to cryptic and frustrating errors. One such classic example is:
Uncaught Error: Objects are not valid as a React child (found: object with keys {email, name}).
In this guide, we'll break down this error, understand what causes it, and build a complete step-by-step form using useState
— the right way.
The Problem Code
import React, { useState } from 'react';
export const Forms = () => {
const [formData, setFormData] = useState({
email: '',
name: '',
});
return (
<form autoComplete='off' className='w-50'>
<div className="mb-3">
<label className="form-label">Email:</label>
<input type="email" className='form-control' name='email' />
</div>
<div className="mb-3">
<label className="form-label">Name:</label>
<input type="text" className='form-control' name='name' />
</div>
<pre>{ formData }</pre> {/* 🚨 This is the error */}
</form>
);
};
Why This Fails
You're trying to render an object directly with { formData }
, but React can only render strings, numbers, arrays, or elements — not plain objects.
This line:
<pre>{ formData }</pre>
throws:
Uncaught Error: Objects are not valid as a React child
The Correct Solution
Use JSON.stringify()
to serialize the object:
<pre>{ JSON.stringify(formData, null, 2) }</pre>
Step-by-Step Working Example
import React, { useState } from 'react';
export const Forms = () => {
const [formData, setFormData] = useState({
email: '',
name: '',
});
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};
return (
<form autoComplete='off' className='w-50'>
<div className="mb-3">
<label className="form-label">Email:</label>
<input
type="email"
name="email"
className='form-control'
value={formData.email}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label className="form-label">Name:</label>
<input
type="text"
name="name"
className='form-control'
value={formData.name}
onChange={handleChange}
/>
</div>
<h5 className='mt-3'>Form JSON Output:</h5>
<pre>{ JSON.stringify(formData, null, 2) }</pre>
</form>
);
};
Key Concepts
Concept | Purpose |
---|---|
useState() |
Hook for tracking component state |
handleChange() |
General handler for all inputs |
...prev |
Spread operator to retain previous state |
JSON.stringify() |
Converts JS object to renderable string |
Summary
React doesn’t allow rendering of plain JavaScript objects directly inside JSX. You must convert objects to strings with JSON.stringify()
or display individual properties.
Mastering these basics of state handling and JSX rendering will make you a confident React developer.
⚠️ Always remember: Render strings, not raw objects.
#react #javascript #hooks #formhandling #json #frontend #architecture
Top comments (0)