Design Converter
Education
Last updated on Feb 10, 2025
•4 mins read
Last updated on Feb 10, 2025
•4 mins read
Software Development Executive - I
Builds things that work. And if it doesn’t, he’ll fix it — with Neovim, of course.
Are you struggling with handling user input in your React forms?
A single-line input works well for names or emails, but what happens when users need to write longer messages or detailed feedback? This is where a React text area becomes useful.
For example, a feedback form with only a single-line input can be frustrating for users who want to share more detailed thoughts. A textarea allows multiline input, making it ideal for comments, messages, or descriptions.
This blog will explain how to add a textarea to a React app, covering state management, form submission, and real-time validation.
A textarea element in HTML is used for multiline text input. In React, it is controlled and rendered as part of a React component. Depending on how you manage the textarea value, you can implement it as either a controlled component or an uncontrolled component.
In controlled components, the textarea value is bound to a state variable. React takes full control of the value and updates it every time the user types. This makes it easier to handle form submission and validation.
In contrast, uncontrolled components rely on the textarea’s initial value and are managed using DOM elements.
Here’s how you can create a controlled component with a textarea:
1import React, { useState } from 'react'; 2 3function CommentForm() { 4 const [comment, setComment] = useState(''); // state variable for textarea value 5 6 const handleChange = (event) => { 7 setComment(event.target.value); 8 }; 9 10 const handleSubmit = (event) => { 11 event.preventDefault(); // Prevent form submission 12 console.log('Submitted comment:', comment); 13 }; 14 15 return ( 16 <form onSubmit={handleSubmit}> 17 <label htmlFor="comment">Your Comment:</label> 18 <textarea 19 id="comment" 20 name="comment" 21 value={comment} // controlled textarea 22 onChange={handleChange} // onchange event handler 23 /> 24 <button type="submit">Submit</button> 25 </form> 26 ); 27} 28 29export default CommentForm;
In this example, the textarea value is controlled by the React state (comment). Every time the user types, the handleChange event handler updates the state, ensuring that the current value is reflected in the textarea element.
For less frequent updates, you might use an uncontrolled component:
1import React, { useRef } from 'react'; 2 3function FeedbackForm() { 4 const commentRef = useRef(null); 5 6 const handleSubmit = (event) => { 7 event.preventDefault(); 8 console.log('Submitted comment:', commentRef.current.value); 9 }; 10 11 return ( 12 <form onSubmit={handleSubmit}> 13 <label htmlFor="feedback">Feedback:</label> 14 <textarea id="feedback" name="feedback" ref={commentRef} defaultValue="Enter your feedback" /> 15 <button type="submit">Submit</button> 16 </form> 17 ); 18} 19 20export default FeedbackForm;
In this case, the textarea element’s value is accessed using commentRef and not updated on each user interaction.
To collect form data from a textarea component, you should implement an onchange event handler and manage the state variable for its input value. This is crucial for validation and providing a smooth user experience.
Setting an initial value for a textarea is simple with the defaultValue prop:
1<textarea defaultValue="This is the initial content" />
The defaultValue prop differs from the value prop. While defaultValue is used for uncontrolled components, value is reserved for controlled components.
Validation in React textareas is crucial for ensuring that users provide the correct input. For instance, you can display an error message if the textarea is left empty:
1if (!comment.trim()) { 2 setErrorMessage('Comment cannot be empty'); 3}
Use React state to display or hide error messages based on validation logic.
Managing focus on a textarea can improve accessibility and user experience. The onFocus and onBlur event handlers detect when the textarea loses focus.
1<textarea onFocus={() => console.log('Textarea focused')} onBlur={() => console.log('Textarea lost focus')} />
To prevent user edits, set a textarea as read-only or disabled:
1<textarea readOnly value="This is read-only text" /> 2<textarea disabled defaultValue="This textarea is disabled" />
To ensure your React textarea looks professional and responsive, apply custom styles using CSS. For instance:
1textarea { 2 width: 100%; 3 height: 150px; 4 padding: 10px; 5 font-size: 16px; 6}
• Comment sections
• Message inputs
• Contact forms
• Multiline input for JSON or code snippets
These are just some form elements that leverage the textarea component for handling user input.
Implementing a React text area as a controlled component or uncontrolled component provides flexibility for handling user interactions. Whether you need real-time validation, dynamic updates, or an optimized way to handle form submission, mastering the React textarea will make your web development more efficient and user-friendly.
By managing the textarea value with a state variable and using appropriate event handlers, you ensure a consistent user experience. Apply these best practices in your React components, and your forms will always feel smooth and intuitive.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.