How to Handle Form in React: Controlled Components Explained
controlled components where form inputs are tied to state variables. Use onChange handlers to update state and onSubmit to process the form data.Why This Happens
When you try to use a form input in React without connecting it to state, the input behaves unexpectedly or React shows warnings. This happens because React needs to control the input's value to keep the UI and data in sync.
import React from 'react'; function MyForm() { return ( <form> <input type="text" /> <button type="submit">Submit</button> </form> ); } export default MyForm;
The Fix
Make the input a controlled component by linking its value to React state and updating that state on every change. This keeps React in control and avoids warnings.
import React, { useState } from 'react'; function MyForm() { const [name, setName] = useState(''); const handleChange = (event) => { setName(event.target.value); }; const handleSubmit = (event) => { event.preventDefault(); alert(`Form submitted with name: ${name}`); }; return ( <form onSubmit={handleSubmit}> <label htmlFor="name">Name:</label> <input id="name" type="text" value={name} onChange={handleChange} aria-label="Name input" /> <button type="submit">Submit</button> </form> ); } export default MyForm;
Prevention
Always use controlled components for form inputs in React. Initialize state for each input, update state on onChange, and handle form submission with onSubmit. Use semantic HTML and accessibility attributes like aria-label or label tags for better user experience.
Use React linting tools like eslint-plugin-react-hooks to catch common mistakes early.
Related Errors
Common related errors include:
- Uncontrolled to controlled input warning: Happens when input value changes from undefined to a string. Fix by initializing state properly.
- Form not submitting: Usually caused by missing
event.preventDefault()in submit handler. - Input not updating: Happens if
valueis set butonChangedoes not update state.