Skip to content

Instantly share code, notes, and snippets.

@Sachin-chaurasiya
Last active April 26, 2024 09:45
Show Gist options
  • Save Sachin-chaurasiya/04ef328c3db93947186766a1fd5f1223 to your computer and use it in GitHub Desktop.
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
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