Last active
July 20, 2024 00:48
-
-
Save Sachin-chaurasiya/04ef328c3db93947186766a1fd5f1223 to your computer and use it in GitHub Desktop.
A simple custom hook to automatically resize the text area based on the content
This file contains 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
import { useLayoutEffect } from 'react'; | |
const useAutoSizeTextArea = ( | |
id: string, | |
textAreaRef: HTMLTextAreaElement | null, | |
value: string | |
) => { | |
// this will calculate the height of textArea before DOM paints | |
useLayoutEffect(() => { | |
const textArea = textAreaRef ?? document.getElementById(id); | |
if (textArea) { | |
// We need to reset the height momentarily to get the correct scrollHeight for the textarea | |
textArea.style.height = '0px'; | |
const scrollHeight = textArea.scrollHeight; | |
textArea.style.height = scrollHeight + 'px'; | |
} | |
}, [textAreaRef, id, value]); | |
}; | |
export default useAutoSizeTextArea; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment