React Mastery / React Basics

Basics Of Form Handling

πŸ“‹ What Is Form Handling in React?

Form handling refers to managing user input in a form (like text boxes, checkboxes, radio buttons, etc.) and responding to form submissions.

React handles forms using controlled components, where form inputs are tied to component state.


🧩 Controlled vs Uncontrolled Components

  • Controlled Component:

    The form input is connected to useState.

    Example: <input value={name} onChange={handleChange} />

  • Uncontrolled Component:

    React does not control the input; data is accessed via refs. (More about this in coming chapters)

Beginners should start with controlled components for easier data tracking.


🧠 Key Concepts in Form Handling

a. useState to store form values:

You store each input’s value in a state variable.

const [name, setName] = useState('');

b. onChange to handle user input:

Update state when user types or interacts.

<input value={name} onChange={(e) => setName(e.target.value)} />

c. onSubmit to handle form submission:

Prevent default behavior and take action (like validation or sending data).

<form onSubmit={handleSubmit}>
  <button type="submit">Submit</button>
</form>


βœ… Why Use Controlled Components?

  • React is fully in control of the form state.

  • Easier to implement validation, conditional UI, and form resets.

  • Enables real-time input processing (e.g., live search, character limits).


πŸ” Common Form Elements Handled in React

  • <input type="text"> β†’ for text values

  • <textarea> β†’ for multiline text

  • <select> and <option> β†’ for dropdowns

  • <input type="checkbox"> β†’ use checked instead of value

  • <input type="radio"> β†’ usually paired with a name attribute