Skip to content

Instantly share code, notes, and snippets.

@uonr
Last active April 12, 2019 19:14
Show Gist options
  • Save uonr/729687be9dec9ec70633be1fb4dcf87f to your computer and use it in GitHub Desktop.
Save uonr/729687be9dec9ec70633be1fb4dcf87f to your computer and use it in GitHub Desktop.
React Hooks for Textarea Auto Height
const useAutoHeight = (text: string, inputRef: React.RefObject<HTMLTextAreaElement>) => {
const threshold = 4;
const additionPx = 2;
const prevText = useRef(text);
useEffect(() => {
const input = inputRef.current;
if (input) {
const isContentReduce = text.length < prevText.current.length;
let oldHeightStyle = null;
const height = input.clientHeight;
if (isContentReduce) {
oldHeightStyle = input.style.height;
input.style.height = '5px';
}
const scrollHeight = input.scrollHeight;
if (Math.abs(height - scrollHeight) > threshold) {
input.style.height = `${scrollHeight + additionPx}px`;
} else if (isContentReduce) {
input.style.height = oldHeightStyle;
}
}
prevText.current = text;
}, [text]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment