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)returningvalues,errors,handleChange(event)(updates the field named byevent.target.name) andhandleSubmit(onValid), which returns a submit handler that prevents the reload, runsvalidate(values)and callsonValid(values)only when it returns no errors. - The login form has controlled inputs named
userandpasswordand a submit button. Its validate givesEnter a user namefor an empty user andUse at least 6 charactersfor a password shorter than 6. - Show each error in a
pwith the classerrorand the attributedata-fieldset to the field's name, under its field. On success, show apwith the classwelcome: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>
);
}