To improve the user experience for the message field so that it grows with the content (up to a point) and then shows scrolling only when necessary, you can use a combination of resize-none, overflow-auto, and dynamically adjusting the height based on the content.
Here’s how you can update your Text Message Section to make the textarea auto-grow with the text input:
✅ Updated Textarea Auto-Grow Logic
You'll need to:
- Use a
<textarea> with ref to access its DOM node.
- Dynamically adjust its height using JavaScript inside the
onChange handler.
✅ Updated Code Snippet
Update your imports if needed, and include this helper function in your component:
import { useRef } from 'react';
Inside your component:
const textareaRef = useRef(null);
// Auto resize function
const autoResize = () => {
const textarea = textareaRef.current;
if (textarea) {
textarea.style.height = 'auto'; // Reset height
textarea.style.height = `${Math.min(textarea.scrollHeight, 300)}px`; // Max height before scroll
}
};
Now, modify your textarea and wrap it in a container for better control:
{/* Text Message Section */}
<div className="bg-gray-800/80 backdrop-blur-sm border border-gray-700/50 p-6 rounded-xl shadow-2xl flex flex-col">
<h2 className="text-lg font-semibold mb-4">Send Text Message</h2>
{/* Wrapper for controlled resizing */}
<div className="relative flex-1 min-h-[100px] max-h-[300px] overflow-hidden">
<textarea
ref={textareaRef}
value={message}
onChange={(e) => {
setMessage(e.target.value);
autoResize(); // Adjust height on every change
}}
onKeyDown={handleKeyPress}
placeholder="Type your message (Ctrl+Enter to send)"
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none overflow-auto"
style={{ height: 'auto' }}
/>
</div>
<button
onClick={sendTextMessage}
disabled={!message.trim() || !connectionRef.current}
className="mt-4 w-full px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg transition-colors"
>
Send Message
</button>
</div>
✅ Explanation:
-
min-h-[100px] max-h-[300px] overflow-hidden on the wrapper ensures:
- The textarea starts at a minimum height.
- It expands up to 300px.
- Beyond that, it won’t grow further — but the internal
textarea will scroll (overflow-auto).
-
autoResize() sets the height dynamically to fit the content, but never more than 300px.
-
resize-none: Prevents manual resizing by the user.
-
overflow-auto: Adds scrollbars only when content exceeds the maximum height.
✅ Optional – Initial Load Resize
If you're pre-filling the message (e.g., editing), trigger the resize on mount too:
useEffect(() => {
autoResize();
}, []);
✅ Final Result
This makes the message box behave like this:
- Starts small.
- Grows as the user types.
- Stops growing after reaching 300px.
- Scrolls instead of getting cut off or becoming too tall.
Let me know if you'd like a reusable component version of this!