There is my code:
import { useState } from "react";
function Form(){
const [inputs, setInputs] = useState({});
const handleChange = e =>{
const name = e.target.name;
const value = e.target.value;
setInputs(values=>({...values, [name]:value}));
}
const handleSubmit = (e)=>{
e.preventDefault();
console.log(inputs.name, inputs.profession, inputs.age);
}
return(
<>
<div className="d-flex justify-content-center mt-4">
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Ad Soyad</label>
<input name="name" id="name" className="form-control" required value={inputs.name || ""} onChange={handleChange}/>
</div>
<div className="form-group mt-2">
<label htmlFor="profession">Meslek</label>
<select className="form-control" value={inputs.profession || ""} onChange={handleChange}>
<option>Seçim yapınız...</option>
</select>
</div>
<div className="form-group mt-2">
<label htmlFor="age">Yaş</label>
<input name="age" id="age" className="form-control" min="18" required value={inputs.age || ""} onChange={handleChange}></input>
</div>
<div className="form-group mt-2">
<button type="submit" className="btn btn-outline-primary w-100">Kaydet</button>
</div>
</form>
</div>
</>
);
}
export default Form;
And I have a question about this part of code:
const handleChange = e =>{
const name = e.target.name;
const value = e.target.value;
setInputs(values=>({...values, [name]:value}));
}
in here, there is a setInputs() and,
setInputs(values=>({...values, [name]:value}));
Why do we wrap name with square brackets? I searched from internet and they say, "name is a dynamic variable so that we use square brackets. Dynamic variable means the variable value changes.". When I read this, another question came to my mind that Why don't we use square brackets with value(setInput()'s value)? Because this value changes every time when we typed to input areas. Because value represent this changes in input areas. So, value should be dynamic variable. If it is, why dont we wrap value with square brackets? Did I understand everything wrong? I need help.
To sum up, I have two questions: 1-Why do we wrap name with square brackets? 2-Why don't we wrap value with square brackets?
Thank you.
I need to get answers to my questions