Skip to main content

Forms

Forms in React work differently than in plain HTML. Instead of letting the DOM manage form state, React components control the input values using state.

Controlled Components

A controlled component is an input whose value is controlled by React state:
Why controlled components?
  • React state is the single source of truth
  • Easy to modify or validate input
  • Consistent behavior across all inputs
  • Simple to implement conditional logic

Handling Different Input Types

Text Inputs

Checkboxes

Radio Buttons

Select Dropdowns

Form Submission

Handle form submission with onSubmit:

Managing Multiple Inputs

Use a single change handler for multiple inputs:

Form Validation

Validation strategies:
  • Validate on submit (less intrusive)
  • Validate on blur (immediate feedback)
  • Validate on change (real-time feedback)
  • Combine strategies for best UX

Real-time Validation

Validate fields as the user types:

Complete Contact Form Example

Best Practices

Form best practices:
  • Always use controlled components for predictable behavior
  • Prevent default form submission with e.preventDefault()
  • Validate on both client and server side
  • Provide clear, immediate error feedback
  • Disable submit button during submission
  • Clear errors when user corrects input
  • Use semantic HTML (labels, fieldsets, etc.)
  • Make forms accessible (ARIA labels, keyboard navigation)

Next Steps

You now have a solid foundation in React forms! Explore more advanced topics:
  • State management - Use Context API or Redux for complex form state
  • Form libraries - Try Formik or React Hook Form for advanced features
  • Server validation - Implement server-side validation and error handling
  • File uploads - Handle file inputs and multipart form data