javascriptreactjsreact-hooksuse-state

How can I store and update multiple values in React useState?


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?


Solution

  • 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}
       />
       // ...
    )