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

Conceptual understanding for Destructuring and State in React

Below code works fine. I just want to understand that after destructuring of name and value from e.target, why name needs to be wrapped in square brackets while setting data. Why can’t we use variable name without square brackets.

  function handleChange(e) {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  }

>Solution :

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

In your case, you would have a formData object with keys that may look like this:

{
  firstName: 'John',
  lastName: 'Doe'
}  

If you would update the object like in your example, you would get the key from your input event which would be dynamic and set by the name prop of the input element, "firstName" for example.
So in the case

{
  ...formData,
  [name]: value,
}

the outcome would actually be

{
  firstName: "Some new value", // Content of the variable value
  lastName: "Doe",
}

But if you were to leave out the square brackets, the name variable wouldn’t be used as key, you would literally use the string value "name" as the key, so:

{
  firstName: "John",
  lastName: "Doe",
  name: "Some new value", // Content of the variable value
}

which is not what you want.

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