auto-expanding-text-area.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { useEffect, useRef } from 'react'
  2. import { callFnsInSequence } from '../../utils/functions'
  3. import { MergeAndOverride } from '../../../../types/utils'
  4. export const resetHeight = (
  5. e:
  6. | React.ChangeEvent<HTMLTextAreaElement>
  7. | React.KeyboardEvent<HTMLTextAreaElement>
  8. ) => {
  9. const el = e.target as HTMLTextAreaElement
  10. window.requestAnimationFrame(() => {
  11. const curHeight = el.offsetHeight
  12. const fitHeight = el.scrollHeight
  13. // clear height if text area is empty
  14. if (!el.value.length) {
  15. el.style.removeProperty('height')
  16. }
  17. // otherwise expand to fit text
  18. else if (fitHeight > curHeight) {
  19. el.style.height = `${fitHeight}px`
  20. }
  21. })
  22. }
  23. type AutoExpandingTextAreaProps = MergeAndOverride<
  24. React.ComponentProps<'textarea'>,
  25. {
  26. onResize?: () => void
  27. }
  28. >
  29. function AutoExpandingTextArea({
  30. onChange,
  31. onResize,
  32. ...rest
  33. }: AutoExpandingTextAreaProps) {
  34. const ref = useRef<HTMLTextAreaElement>(null)
  35. const isFirstResizeRef = useRef(true)
  36. useEffect(() => {
  37. if (!ref.current || !onResize || !('ResizeObserver' in window)) {
  38. return
  39. }
  40. const resizeObserver = new ResizeObserver(() => {
  41. // Ignore the resize that is triggered when the element is first
  42. // inserted into the DOM
  43. if (isFirstResizeRef.current) {
  44. isFirstResizeRef.current = false
  45. } else {
  46. // Prevent errors like "ResizeObserver loop completed with undelivered
  47. // notifications" that occur if onResize does something complicated.
  48. // The cost of this is that onResize lags one frame behind, but it's
  49. // unlikely to matter.
  50. // Wrap onResize to prevent extra parameters being passed
  51. window.requestAnimationFrame(() => onResize())
  52. }
  53. })
  54. resizeObserver.observe(ref.current)
  55. return () => {
  56. resizeObserver.disconnect()
  57. }
  58. }, [onResize])
  59. return (
  60. <textarea
  61. onChange={callFnsInSequence(onChange, resetHeight)}
  62. {...rest}
  63. ref={ref}
  64. />
  65. )
  66. }
  67. export default AutoExpandingTextArea