Skip to main content

Search

Search problems, hooks, and pages

Form Handling

Build a controlled form with multiple inputs, inline validation, and a success state after submission. The foundation of every real-world React form.

Requirements

  • Three fields: Name, Email, Message (textarea)
  • All fields are controlled (value + onChange)
  • Single handleChange function handles all fields via e.target.name
  • Validate on submit: required fields, valid email format, message min-length
  • Show inline error messages below each invalid field
  • Clear a field's error as soon as the user starts typing in it
  • Show a success state with submitted values after valid submission

Key Patterns

form state: { name, email, message }errors state: Partial<Record<keyof Form, string>>Single handleChange: e.target.name as keyvalidate() returns errors objecte.preventDefault() in handleSubmit

Important

Interview Tip

The single handleChange pattern is the key: function handleChange(e) { setForm(prev => ({ ...prev, [e.target.name]: e.target.value })) }. Each input must have a name attribute matching the state key. Validate on submit (not on every keystroke) but clear errors on input change for good UX. Never store derived values like 'isValid' in state — check Object.keys(errors).length === 0 inline.