diff --git a/.changeset/fluffy-plums-grin.md b/.changeset/fluffy-plums-grin.md new file mode 100644 index 00000000000..aa4b5bd843a --- /dev/null +++ b/.changeset/fluffy-plums-grin.md @@ -0,0 +1,7 @@ +--- +"@aws-amplify/ui-react": patch +--- + +fix(textarea): autoresize textarea resets when value is empty + +There was a bug with the autoresize text area where it would not reset the size when a value was cleared. This fixes that bug diff --git a/packages/react/src/primitives/TextArea/__tests__/useAutoresizeTextarea.test.ts b/packages/react/src/primitives/TextArea/__tests__/useAutoresizeTextarea.test.ts new file mode 100644 index 00000000000..bc81da74c3d --- /dev/null +++ b/packages/react/src/primitives/TextArea/__tests__/useAutoresizeTextarea.test.ts @@ -0,0 +1,41 @@ +import { renderHook } from '@testing-library/react-hooks'; +import { useAutoresizeTextArea } from '../useAutoresizeTextarea'; + +describe('useAutoresizeTextArea', () => { + let textAreaRef: HTMLTextAreaElement; + + beforeEach(() => { + textAreaRef = document.createElement('textarea'); + jest.spyOn(window, 'addEventListener'); + jest.spyOn(window, 'removeEventListener'); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('should set the height of the textarea', () => { + renderHook(() => useAutoresizeTextArea(textAreaRef, 'initial value')); + expect(textAreaRef.style.height).toBe('0px'); + }); + + it('should add and remove event listener for window resize', () => { + const { unmount } = renderHook(() => useAutoresizeTextArea(textAreaRef)); + expect(window.addEventListener).toHaveBeenCalledWith( + 'resize', + expect.any(Function) + ); + + unmount(); + expect(window.removeEventListener).toHaveBeenCalledWith( + 'resize', + expect.any(Function) + ); + }); + + it('should not throw error when textAreaRef is null', () => { + expect(() => { + renderHook(() => useAutoresizeTextArea(null)); + }).not.toThrow(); + }); +}); diff --git a/packages/react/src/primitives/TextArea/useAutoresizeTextarea.ts b/packages/react/src/primitives/TextArea/useAutoresizeTextarea.ts index 49698d279a7..5bb139a0bfb 100644 --- a/packages/react/src/primitives/TextArea/useAutoresizeTextarea.ts +++ b/packages/react/src/primitives/TextArea/useAutoresizeTextarea.ts @@ -7,7 +7,7 @@ export const useAutoresizeTextArea = ( ): void => { useEffect(() => { const resizeTextArea = () => { - if (textAreaRef && value) { + if (textAreaRef) { // We need to reset the height momentarily to get the correct scrollHeight for the textarea textAreaRef.style.height = 'auto'; const { scrollHeight } = textAreaRef;