React Form
A form in React is used to collect user input, like a name, email, or password.
React Forms are used to collect user input, just like in plain HTML. However, React gives you more control over form elements using state and event handlers. There are two main ways to work with forms in React:
1. Controlled Components
In controlled components, form inputs (like <input>
, <textarea>
, etc.) are controlled by React state.
Key Concepts:
- The value of the form element is set by useState.
- You update the state using onChange.
2. Uncontrolled Components
In uncontrolled components, React does not control the form values. Instead, you use refs to access the DOM directly.
🆚 Controlled vs Uncontrolled
Feature | Controlled | Uncontrolled |
---|---|---|
Data source | React state | DOM (via ref) |
Validation | Easier | Harder |
Integration | Better with React apps | More like plain HTML |