Last active
April 12, 2019 19:14
-
-
Save uonr/729687be9dec9ec70633be1fb4dcf87f to your computer and use it in GitHub Desktop.
React Hooks for Textarea Auto Height
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
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