1 import { useCallback, useState } from 'react';
3 const getTextAreaRows = ({ el, minRows, maxRows }: { el: HTMLTextAreaElement; minRows: number; maxRows: number }) => {
4 const textAreaLineHeight = +getComputedStyle(el).lineHeight.replace('px', '');
6 const previousRows = el.rows;
8 // Reset rows so we can calculate calculate currentRows correctly
11 const currentRows = Math.min(maxRows, Math.max(minRows, ~~(el.scrollHeight / textAreaLineHeight)));
13 // Set rows attribute directly because React won't update it as it stayed the same
14 if (currentRows === previousRows) {
15 el.rows = currentRows;
21 const useAutoGrow = ({ maxRows = 5, minRows = 1, autoGrow = false }) => {
22 const [rows, setRows] = useState(minRows);
24 const updateTextArea = useCallback(
25 (el: HTMLTextAreaElement) => {
26 setRows(getTextAreaRows({ el, minRows, maxRows }));
37 return { rows, updateTextArea };
40 export default useAutoGrow;