I've a series of user data elements which I'm collecting inside a React component using hooks.
const [mobile, setMobile] = useState('');
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
Each of these are updated as follows.
<input type="text"
className="form-control"
id="mobile"
placeholder="Enter a valid mobile number"
onChange={event => {setMobile(event.target.value)}}/>
Is there a more succint way to do this using an object as the variable?
Yes. In fact that's how it was designed to be used. You just can't conditionalize the calls to useState because the call order matters to React. The number of times you called useState is tracked and React expects the same amount of calls each time.
myArray. push(1); However, with React, we need to use the method returned from useState to update the array. We simply, use the update method (In our example it's setMyArray() ) to update the state with a new array that's created by combining the old array with the new element using JavaScript' Spread operator.
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}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With