본문 바로가기
FRONTEND/React

220902 React Textarea 컨텐츠 높이 자동 설정

by 또야또야 2022. 9. 2.
반응형

이벤트 없이 자동으로 Textarea 컨텐츠 높이 설정

import React, { useRef, useEffect } from 'react'

const Chat = () => {
  const myRef = useRef<HTMLTextAreaElement>(null)

  // textarea 자동 높이 설정
  useEffect(() => {
    if (myRef.current !== null) {
      myRef.current.style.height = (myRef.current.scrollHeight) + 'px'
    }
  }, [myRef])

  return (
    <div className={ wrapper }>
        { image }

      <div className="-profile">
        <span className="name">{name}</span>

        <div className="-textarea">
        <textarea
          ref={ myRef }
          value={ content }
          readOnly
        />
        </div>
      </div>
    </div>
  )
}

결과물



컨텐츠 내용에 맞춰 높이 설정 완료

반응형

댓글