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 :
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.