File size: 2,441 Bytes
17fcca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"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;