Answer the question
In order to leave comments, you need to log in
How to write states to an object?
The state of the login form is controlled by the useState hook. Each form field has an onChange handler. Upon user input, the corresponding values are written to the state object:
import React, { useState } from 'react';
function Auth(props) {
const [form, setForm] = useState([{
login: '',
password: '',
}]);
return (
<>
<div className="login-form">
<input type="text" onChange={ e => { setForm({ login: e.currentTarget.value }) } }/>
<br/>
<input type="text" onChange={ e => { setForm({ password: e.currentTarget.value }) } }/>
<br/>
<button>auth</button>
{ form.login }--
{ form.password }
</div>
</>
);
}
export default Auth;
{ form.login }--
{ form.password }
Answer the question
In order to leave comments, you need to log in
<input type="text" onChange={e => setForm({ ...form, login: e.target.value })} />
<input type="text" onChange={e => setForm({ ...form, password: e.target.value })} />
Yes, that's right, you are overwriting the state, so you need to use the spread operator to save the old field values. As stated in the answers above. From myself, I can add something that it would not be bad to immediately use the react-hook-form library. It will reduce the number of renders, which will have a good effect on performance.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question