Search code examples
reactjsinputrerender

Why input value isn't changed when re-render is occured by object state update


I am studying React through React Offical Document.

I have question about this challenge.

(https://react.dev/learn/updating-objects-in-state#challenges

https://codesandbox.io/s/rztj2r?file=/src/App.js&utm_medium=sandpack)

Assume that the given code is executed as it is without modification,

I understand why {player.score} is disappeared when re-render is occured by handleLastNameChange() event handler called.

But I can't understand why {player.firstName} isn't disappeard when re-render is occured by handleLastNameChange() event handler called.

I expected {player.firstName} is disappeared when re-render is occured by handleLastNameChange() event handler called, but it doesn't work.


Solution

  • But I can't understand why {player.firstName} isn't disappeard when re-render is occured by handleLastNameChange() event handler called.

    If you look in the log, you'll see this

    Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components

    There are two ways an input can be used: controlled, and uncontrolled. For controlled, you pass in a string to the value prop, and react will keep the input in sync with that prop. For uncontrolled, you pass in undefined for the value prop, and then the input will handle its state itself and ignore the prop.

    So when the page started, you were passing in a string and thus controlling the input. Then when handleLastNameChange is called, the state accidentally sets firstName to undefined, which gets passed into the input. This flips the component to uncontrolled mode, which is not something it is built for. So it fires off the warning and then continues showing what it was previously showing, until something causes it to change.