2

My onChange handler for submitting a form with multiple input values and takes in whatever the name attribute of the given input field is. So i basically know what this code does, but i don't know exactly what happens under the hood.

Why the brackets in [e.target.name] ?
I also know that in this case setFormData({ ...formData, name: e.target.value}); the function would every time just change the value of the input field with the attribute name.

const Register = ({ setAlert, register, isAuthenticated }) => {
  const [formData, setFormData] = useState({
    name:"",
    email:"",
    password: "",
    password2: ""
  }); 

  const {name, email, password, password2} = formData;

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

Would be nice if somebody would know it.

Andreas
  • 21,535
  • 7
  • 47
  • 56
BitFlippa
  • 51
  • 5

1 Answers1

3
  • the spread operator : ... is for take all properties(with the values of course) of an array or object

    const arr = ["a", "b","c"];
    
    const arr2 = [...arr, "d"];
    
    // arr2 -> ["a", "b","c", "d"]
    
  • the backets are used to put a variable value as a property

    const prop = "myProp";
    const obj = {[prop] : "value"}
    // obj -> {myProp : value}
    
Maxime Girou
  • 1,511
  • 2
  • 16
  • 32