1

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
  • 19,756
  • 7
  • 41
  • 49
DeLean
  • 31
  • 4
  • 3
    Does this answer your question? [Square Brackets Javascript Object Key](https://stackoverflow.com/questions/32515598/square-brackets-javascript-object-key) – gurisko Sep 28 '20 at 16:20
  • yess, definitively thank you very much :) – DeLean Sep 28 '20 at 17:36

1 Answers1

1
  • 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,415
  • 2
  • 11
  • 26