1
const handleChange = (event) => {
    const { name, value } = event.target;

Here is [name] that is inside the square bracket. I know what it's doing but I just want to know what was the logic under the hood to use this logic?

setFormFields({ ...formFields, [name]: value });
    console.log(formFields);
  };

If it's array destructuring why and how is it working and why not object destructuring and what is the reason behind using this logic?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

In your first example, const { name, value } = event.target; is object destructuring, pulling the name and value properties off of event.target;

While your second example looks the same, it's the opposite - instead of destructuring an object into variables you're creating a new object. Somewhere above that line, there's a variable called name.

You can think of the example like this:

const name = 'someKey';
const value = 'someValue';
const formFields = { keyOne: 'one' };

const newObject = { ...formFields, [name]: value }; // { keyOne: 'one', someKey: 'someValue' };
Tom
  • 7,640
  • 1
  • 23
  • 47