I have a problem with react. with a form, I created more inputs that are controlled. I created a function that runs when the form changes. which but updates a state. but reacte gives me an error.
VM2529 react_devtools_backend.js:4026 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.
handleChange func:
let DefaultValue = {
firsName: '',
lastname: '',
email: '',
message: ''
}
const [output, setOutput] = useState(DefaultValue)
const handleChange = (e) => {
setOutput({ [e.target.name]: e.target.value });
}
thank you for your reply.
CodePudding user response:
setOutput({ [e.target.name]: e.target.value });
This will not be merged with the old state, it will replace the old state. So if they change lastName
, the new state will be { lastName: "some string" }
, and all other values will be undefined.
Instead, you need to copy all the other values from the old state:
setOutput(prev => ({
...prev,
[e.target.name]: e.target.value
});