Forked from KristofferEriksson/useDynamicTextareaSize.ts
Created
February 2, 2024 04:25
-
-
Save nova4u/cf0a63c32448439fcfd0b251a23cd190 to your computer and use it in GitHub Desktop.
A simple React hook to dynamically adjust the height of a textarea based on its content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Custom hook for dynamically resizing a textarea to fit its content. | |
| * @param {React.RefObject<HTMLTextAreaElement>} textareaRef - Reference to the textarea element. | |
| * @param {string} textContent - Current text content of the textarea. | |
| * @param {number} maxHeight - Optional: maxHeight of the textarea in pixels. | |
| */ | |
| import { useEffect } from "react"; | |
| const useDynamicTextareaSize = ( | |
| textareaRef: React.RefObject<HTMLTextAreaElement>, | |
| textContent: string, | |
| // optional maximum height after which textarea becomes scrollable | |
| maxHeight?: number | |
| ): void => { | |
| useEffect(() => { | |
| const currentTextarea = textareaRef.current; | |
| if (currentTextarea) { | |
| // Temporarily collapse the textarea to calculate the required height | |
| currentTextarea.style.height = "0px"; | |
| const contentHeight = currentTextarea.scrollHeight; | |
| if (maxHeight) { | |
| // Set max-height and adjust overflow behavior if maxHeight is provided | |
| currentTextarea.style.maxHeight = `${maxHeight}px`; | |
| currentTextarea.style.overflowY = contentHeight > maxHeight ? "scroll" : "hidden"; | |
| currentTextarea.style.height = `${Math.min(contentHeight, maxHeight)}px`; | |
| } else { | |
| // Adjust height without max height constraint | |
| currentTextarea.style.height = `${contentHeight}px`; | |
| } | |
| } | |
| }, [textareaRef, textContent, maxHeight]); | |
| }; | |
| export default useDynamicTextareaSize; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment