Chapter 9: Forms in React

Almost every real app has forms: login, signup, search, comments, checkout, contact us… you name it. Today we’ll learn how to handle forms the React way — correctly, efficiently, and in a way that feels natural.

We’ll go slowly and clearly, like I’m sitting next to you in Mumbai showing you live on the screen.

1. Controlled vs Uncontrolled Components (The Big Decision)

Feature Controlled Components (Recommended 99% of the time) Uncontrolled Components (Rarely used)
State React controls the value via state The DOM controls the value
Value value={state} + onChange to update state No value, use defaultValue
Access value Always know the current value in React state Need ref to read value when needed
Validation Easy — validate in state Harder — read value on submit
Instant feedback Real-time validation, formatting, etc. Only on submit
When to use Almost everything: login, search, todo add, etc. Very simple forms, legacy code, or file inputs

Official React recommendation in 2026: Use controlled components for most forms. They give you full control, make validation easy, and keep everything in sync with React state.

2. Handling Common Form Inputs (Controlled Way)

Let’s build a beautiful, complete registration form that handles:

  • Text input
  • Email
  • Password
  • Textarea
  • Select (dropdown)
  • Checkbox
  • Radio buttons

Create new file: src/components/RegistrationForm.tsx

tsx

Use in App.tsx:

tsx

3. Form Submission – Summary of Best Practices

  1. Always use e.preventDefault() in onSubmit
  2. Use controlled inputs → value + onChange
  3. Use one state object for the whole form (or separate states — both fine)
  4. Use single handleChange function with name attribute
  5. Validate on submit (or better — real-time validation)
  6. Show success/error messages after submit
  7. Disable button while submitting (in real apps)

Summary – Chapter 9 Key Takeaways

  • Controlled components = React state controls input value → best for most cases
  • Use value={state} + onChange={updateState}
  • Use one handler for all inputs by using name attribute
  • textarea, select, checkbox, radio work almost the same way
  • Always e.preventDefault() on form submit
  • Real-time validation & feedback = great user experience

Mini Homework

  1. Add real-time validation:
    • Show red border + error message if email is invalid
    • Show password strength indicator
  2. Bonus: Add a “Confirm Password” field and check if it matches

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *