0

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 });
  }
  • Does this answer your question? [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – pilchard Jul 20 '23 at 09:08

1 Answers1

0

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.

joobacca
  • 24
  • 2
  • So, by using square brackets here. I am just telling javascript/react that its a key. Am i correct? – Ashish Gahlot Jul 20 '23 at 09:22
  • Vote to close as duplicate. Computed properties have ample dupe targets – pilchard Jul 20 '23 at 09:25
  • 2
    @AshishGahlot You are telling it to use the *value assigned to the variable* as a key. see: [Computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names) – pilchard Jul 20 '23 at 09:32