handsome
handsome

Reputation: 2402

how to fix A component is changing an uncontrolled input of type undefined

I´m getting the "A component is changing an uncontrolled input of type undefined to be controlled"

const [user, setUser] = useState({});
const {name} = user;

const handleInputChange = (event) => {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    setUser((prevState) => {
        return {
            ...prevState,
            [name]: value,
        };
    });
};

when I render the person

<input
    name="name"
    value={name}
    onChange={(e) => handleInputChange(e)}
/>

name is undefined so that´s probably why is triggering the warning. but can I just create the name inside user?

I´m getting the expected outcome just want to get rid of the warning

if I do console.log(user) I see the name just fine.

Upvotes: 1

Views: 99

Answers (2)

HermitCrab
HermitCrab

Reputation: 3264

Just make sure value is never undefined:

<input
    name="name"
    value={name || ''}
    onChange={(e) => handleInputChange(e)}
/>

Upvotes: 3

gautamits
gautamits

Reputation: 1292

Just initialise input with empty string when undefined. Warning will go away.

<input
    name="name"
    value={name || ""}
    onChange={(e) => handleInputChange(e)}
/>

Upvotes: 2

Related Questions