Answers for "setState of one element of an object of states"

0

setState of one element of an object of states

function LoginForm() {
  const [form, setState] = useState({
    username: '',
    password: ''
  });

  const printValues = e => {
    e.preventDefault();
    console.log(form.username, form.password);
  };

  const updateField = e => {
    setState({
      ...form,
      [e.target.name]: e.target.value
    });
  };

  return (
    <form onSubmit={printValues}>
      <label>
        Username:
        <input
          value={form.username}
          name="username"
          onChange={updateField}
        />
      </label>
      <br />
      <label>
        Password:
        <input
          value={form.password}
          name="password"
          type="password"
          onChange={updateField}
        />
      </label>
      <br />
      <button>Submit</button>
    </form>
  );
}
Posted by: Guest on July-22-2021

Code answers related to "setState of one element of an object of states"

Code answers related to "Javascript"

Browse Popular Code Answers by Language