AI / app /components /TextField.js
Niansuh's picture
Upload 18 files
17fcca9 verified
"use client";
import { useEffect } from 'react';
const ResponsiveTextarea = ({ maxRows = 10, ...props }) => {
useEffect(() => {
const textarea = document.getElementById('responsive-textarea');
const adjustHeight = () => {
textarea.style.height = 'auto'; // Reset height to auto to recalculate
const lineHeight = parseInt(getComputedStyle(textarea).lineHeight); // Get line height
const rows = (textarea.scrollHeight / lineHeight)-2; // Calculate rows
console.log(rows);
if (rows <= maxRows) {
textarea.style.height = `${(textarea.scrollHeight)/2}px`; // Adjust height based on content
textarea.style.overflowY = 'hidden'; // Hide scrollbar if within limit
} else {
textarea.style.height = `${lineHeight * maxRows}px`; // Cap height at max rows
textarea.style.overflowY = 'auto'; // Show scrollbar if max rows are exceeded
}
};
textarea.addEventListener('input', adjustHeight);
// adjustHeight whenever input changes
textarea.addEventListener('change', adjustHeight);
// Initial adjustment for pre-filled content
adjustHeight();
// Cleanup event listener
return () => {
textarea.removeEventListener('input', adjustHeight);
};
}, [maxRows]);
useEffect(() => {
const textarea = document.getElementById('responsive-textarea');
const adjustHeight = () => {
textarea.style.height = 'auto'; // Reset height to auto to recalculate
const lineHeight = parseInt(getComputedStyle(textarea).lineHeight); // Get line height
const rows = (textarea.scrollHeight / lineHeight)-2; // Calculate rows
console.log(rows);
if (rows <= maxRows) {
textarea.style.height = `${(textarea.scrollHeight)/2}px`; // Adjust height based on content
textarea.style.overflowY = 'hidden'; // Hide scrollbar if within limit
} else {
textarea.style.height = `${lineHeight * maxRows}px`; // Cap height at max rows
textarea.style.overflowY = 'auto'; // Show scrollbar if max rows are exceeded
}
};
adjustHeight();
})
return (
<textarea
id="responsive-textarea"
style={{ resize: 'none', overflowY: 'hidden', display:'flex', alignItems:'center', justifyContent:'center' }}
{...props}
/>
);
};
export default ResponsiveTextarea;