How to Handle Textarea in React: Controlled Component Example
In React, handle a
textarea by making it a controlled component using useState to store its value and updating that state on onChange events. This keeps the textarea value in sync with React state, ensuring reliable input handling.Why This Happens
When you use a textarea in React without controlling its value via state, React does not know about changes inside the textarea. This causes the textarea to behave unexpectedly or not update as you type.
jsx
import React from 'react'; function MyComponent() { return <textarea />; } export default MyComponent;
Output
A textarea appears but typing inside it does not update React state or trigger any React-controlled behavior.
The Fix
Use React state to store the textarea's value and update it on every change. This makes the textarea a controlled component, syncing its displayed value with React state.
jsx
import React, { useState } from 'react'; function MyComponent() { const [text, setText] = useState(''); const handleChange = (event) => { setText(event.target.value); }; return <textarea value={text} onChange={handleChange} aria-label="Input textarea" />; } export default MyComponent;
Output
A textarea that updates its content as you type, with React state always matching the textarea's value.
Prevention
Always use controlled components for form inputs in React to keep UI and state in sync. Use useState or other state management to hold input values. Add aria-label or other accessibility attributes for better user experience.
Linting tools like ESLint with React plugin can warn if you forget to control inputs.
Related Errors
Common related issues include:
- Textarea not updating on typing because
valueis set butonChangeis missing. - Uncontrolled to controlled input warning when switching between controlled and uncontrolled states.
- Forgetting to initialize state causing
undefinedvalue errors.
Key Takeaways
Always control textarea value with React state using useState and onChange.
Controlled components keep UI and state synchronized for reliable input handling.
Add accessibility attributes like aria-label to improve usability.
Use linting tools to catch uncontrolled input mistakes early.