const [data , setData] = ({firstname:'' , lastname:'' , password:''});
const handleChange = (e) => { setData({...data , [e.target.name] : e.target.value })
I am new to react and java script and can't figure out why ...data(for destructuring) is used is handlechange() function and what is the use of [] braces in [e.target.name] : e.target.value
CodePudding user response:
In this case, ...data
(destructuring) is being used so that other attributes already present in data
are not affected by the change to the attribute that triggered the event that is actually calling handleChange()
.
For example, suppose you have a form that has the fields: "Name", "Age", and "Profession". Suppose you fill the form fields in the same above order. As you fill each form field and handleChange()
is called your data
object gets updated:
When filling the name:
{ name: "John" }
When filling age:
{ name: "John", age: "20" }
When filling profession:
{ name: "John", age: "20", profession: "student" }
...data
(destructuring) is a way to ensure the previous attributes are preserved as you add or update new attributes to the data
object.
For the second part of your question, the square brackets are used to ensure javascript will evaluate e.target.name
and use its value as the attribute to be added or updated to data
. The form input fields for this example, should have the name
attributes as "name", "age", and "profession", respectively.
CodePudding user response:
Here is the "long" version of the handleChange function. I think it will help you understand the function mission easier.
cons handleChange = (e) => {
const currentData = data;
currentData[e.target.name] = e.target.value;
setData(currentData)
}
The first is the three dots with an object like ...data
. It's almost the same with Object.assign
. In this case, it help you create a new object from the value of data.
const data = {firstname:'' , lastname:'' , password:''};
const newData = {...data}; // {firstname:'' , lastname:'' , password:''}
The second is the [] braces. If you want to set a property key from a variable inside the {}. You may use the [] braces to wrap this variable.
const key = 'name';
const a = {[key]: 'John'} // {name: 'John'}.
This is not really related to React, you may get the function like this in other places. Some articles you may read about them:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax