Skip to content

Commit 6c27735

Browse files
committed
fix(TextArea): use ResizeObserver for autoSize
1 parent 20ada84 commit 6c27735

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

src/components/fields/TextArea/TextArea.tsx

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { forwardRef, useLayoutEffect, useRef } from 'react';
1+
import { forwardRef, useEffect, useLayoutEffect, useRef } from 'react';
22
import { useControlledState } from '@react-stately/utils';
33
import { useTextField } from 'react-aria';
44

@@ -100,23 +100,26 @@ function TextArea(props: WithNullableValue<CubeTextAreaProps>, ref) {
100100
textarea.style.height = `${totalHeight}px`;
101101
});
102102

103+
const useEnvironmentalEffect =
104+
typeof window !== 'undefined' ? useLayoutEffect : useEffect;
105+
103106
// Call adjustHeight on content change
104-
useLayoutEffect(() => {
107+
useEnvironmentalEffect(() => {
105108
adjustHeight();
106109
}, [inputValue]);
107110

108111
// Also call it on window resize as that can affect wrapping
109-
useLayoutEffect(() => {
110-
if (!autoSize) return;
112+
useEnvironmentalEffect(() => {
113+
if (!autoSize || !inputRef.current) return;
114+
115+
adjustHeight();
111116

112-
const handleResize = () => {
113-
adjustHeight();
114-
};
117+
const resizeObserver = new ResizeObserver(adjustHeight);
115118

116-
window.addEventListener('resize', handleResize);
119+
resizeObserver.observe(inputRef?.current);
117120

118-
return () => window.removeEventListener('resize', handleResize);
119-
}, [adjustHeight, autoSize]);
121+
return () => resizeObserver.disconnect();
122+
}, [autoSize, inputRef?.current]);
120123

121124
return (
122125
<TextInputBase

0 commit comments

Comments
 (0)