Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fonctionnement formulaire contrôlé react?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading