[React] textarea 높이 자동 조절

SEUNGJUN JEONG·2023년 4월 29일
0

WEB Front-End

목록 보기
7/10
post-thumbnail

학교 동아리 프로젝트 팀에서 개발하고 있는 서비스에 이 기능을 한 번 적용 해보았습니다.

입력한 줄 수 만큼 textarea의 높이가 늘어나게 하는 기능입니다.

  const textarea = useRef();
  const handleResizeHeight = () => {
    textarea.current.style.height = "auto"; // 높이 초기화
    textarea.current.style.height = textarea.current.scrollHeight + "px";
  };
  
  return (
  	<textarea
      ref={textarea}
      onInput={handleResizeHeight}
      rows={1}
      className="...(tailwind css)">
    </textarea>

onInput 속성과 useRef을 사용하여 높이를 자동으로 조정하는 간단한 코드입니다.

profile
Microsoft Learn Student Ambassadors

0개의 댓글