Fix the controlled input warning in React
Keep a React text input controlled from its first render by giving it a string value.
You typed a letter into a form field and React logged a warning in the console. "A component is changing an uncontrolled input to be controlled." The field looks fine and the value is right, so something started out as undefined.
import { useState } from 'react'
function NameField({ user }) {
const [name, setName] = useState(user?.name)
return <input value={name} onChange={(e) => setName(e.target.value)} />
}If user has not loaded, name is undefined on the first render. An input with value={undefined} has no value for React to control, so React treats it as uncontrolled and leaves the text to the browser. When name later becomes a string, React takes over, and the warning says it noticed the switch.
I rendered this component with no user, then changed the field to Ada. The field read as an empty string before the change, so nothing looked wrong. On the change React logged this, and the value ended up as Ada:
A component is changing an uncontrolled input to be controlled.
Start with a string
React wants one answer for the whole life of the input. Make that answer "controlled" from the first render, so the value is never undefined.
const [name, setName] = useState(user?.name ?? '')The empty string is what the field already showed, so the screen does not change. I ran the same test again with this line. The warning is gone and the field still ends up as Ada.
Where else it comes from
The same warning appears wherever a value can be undefined at the start. Two places to check:
- A form object built from an API response, where a field is missing until the data arrives:
value={form.email}. - A prop with no default, passed to
valueas it is.
null needs the same fix. I ran the component with null as the starting state and React logged a second warning first: "value prop on input should not be null. Consider using an empty string to clear the component or undefined for uncontrolled components." The controlled warning followed on the first change.
The useState initializer runs on mount, so a later user prop does not populate this field. If you need the loaded name as an editable starting value, mount the form after the data arrives. For values that come straight from props, give the input value={name ?? ''} on each render.