I\'ve a series of user data elements which I\'m collecting inside a React component using hooks.
const [mobile, setMobile] = useState(\'\');
const [username, set
You should add name
attributes to input tags. Each name must refer to key in AllValues
object.
const [allValues, setAllValues] = useState({
mobile: '',
username: '',
email: '',
password: '',
confirmPassword: ''
});
const changeHandler = e => {
setAllValues({...allValues, [e.target.name]: e.target.value})
}
return (
<input type="text"
className="form-control"
id="mobile"
name="mobile"
placeholder="Enter a valid mobile number"
onChange={changeHandler}
/>
// ...
)
The above answer could create issues in some cases, the following should be the right approach.
const [allValues, setAllValues] = useState({
mobile: '',
username: '',
email: '',
password: '',
confirmPassword: ''
});
const changeHandler = e => {
setAllValues( prevValues => {
return { ...prevValues,[e.target.name]: e.target.value}
}
}