27. Forms (Controlled Inputs)
Taking Control of Inputs
In standard HTML, input fields (like <input>, <textarea>, and <select>) maintain their own internal state. If a user types 'Hello', the input stores that text in the DOM. In React, we don't want the DOM managing data—we want React to be the 'Single Source of Truth'. We solve this using Controlled Components.
What is a Controlled Input?
A controlled input is an input field where React entirely dictates what is shown on the screen. We bind the input's value to a React state variable, and we update that state using the onChange event.
Handling Multiple Inputs Safely
If you have a form with 10 inputs (First Name, Last Name, Password, Address...), creating 10 separate useState variables gets incredibly messy. The professional pattern is to use a single state object and dynamically update it using the input's name attribute.
Form Submission
Never rely on action URLs in React forms. Attach an onSubmit handler to the <form> tag itself (not the submit button), and always call e.preventDefault() to stop the browser from refreshing.
Knowledge Check
Ready to test your understanding of 27. Forms (Controlled Inputs)?