React: A form Hook

Most forms repeat the same work: track values, validate, show errors. Put it in a Hook that any form can use.

What to build

A login form built on a reusable useForm Hook.

Requirements

  • Write useForm(initialValues, validate) returning values, errors, handleChange(event) (updates the field named by event.target.name) and handleSubmit(onValid), which returns a submit handler that prevents the reload, runs validate(values) and calls onValid(values) only when it returns no errors.
  • The login form has controlled inputs named user and password and a submit button. Its validate gives Enter a user name for an empty user and Use at least 6 characters for a password shorter than 6.
  • Show each error in a p with the class error and the attribute data-field set to the field's name, under its field. On success, show a p with the class welcome: Welcome, USER.

Constraints

The form component must not call useState itself.

Example

Submitting an empty form shows both errors; "ada" with "secret1" shows "Welcome, ada".

Why it works

The Hook knows nothing about logins, only about values, errors and submitting, so the same Hook can drive any form, while each form brings its own fields and its own validate function.

Hints

Hint 1

useForm(initial, validate) keeps values and errors in state and returns { values, errors, handleChange, handleSubmit }.

Hint 2

handleChange reads event.target.name and value; handleSubmit(onValid) returns an onSubmit handler.

Solution

Show one correct solution (try it yourself first)
import { useState } from "react";

function useForm(initialValues, validate) {
  const [values, setValues] = useState(initialValues);
  const [errors, setErrors] = useState({});

  function handleChange(event) {
    setValues({ ...values, [event.target.name]: event.target.value });
  }

  function handleSubmit(onValid) {
    return (event) => {
      event.preventDefault();
      const found = validate(values);
      setErrors(found);
      if (Object.keys(found).length === 0) onValid(values);
    };
  }

  return { values, errors, handleChange, handleSubmit };
}

function validateLogin(values) {
  const errors = {};
  if (values.user.trim() === "") errors.user = "Enter a user name";
  if (values.password.length < 6) errors.password = "Use at least 6 characters";
  return errors;
}

function LoginForm({ onLogin }) {
  const { values, errors, handleChange, handleSubmit } = useForm({ user: "", password: "" }, validateLogin);
  return (
    <form onSubmit={handleSubmit(onLogin)}>
      <input name="user" value={values.user} onChange={handleChange} />
      {errors.user && (
        <p className="error" data-field="user">
          {errors.user}
        </p>
      )}
      <input name="password" type="password" value={values.password} onChange={handleChange} />
      {errors.password && (
        <p className="error" data-field="password">
          {errors.password}
        </p>
      )}
      <button type="submit">Log in</button>
    </form>
  );
}

export default function App() {
  const [user, setUser] = useState(null);
  return (
    <div>
      <LoginForm onLogin={(values) => setUser(values.user)} />
      {user && <p className="welcome">Welcome, {user}</p>}
    </div>
  );
}

Lesson: Custom Hooks: reusing stateful logic →