Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

박철순

React에서 TextArea 자동 높이 조절 본문

Javascript/React

React에서 TextArea 자동 높이 조절

박철순입니다 2022. 7. 18. 23:58
 const autoResizeTextarea = () => {
    textAreaRef.current.style.height = 'auto';
    textAreaRef.current.style.height = textAreaRef.current.scrollHeight + 'px';
  };
 
 return <textarea ref={textAreaRef} onChange={autoResizeTextarea}/>
textarea {
  overflow-y : hidden; 	
}

scrollHeight로 해당 textArea의 높이값을 가져온다.

그 후 onChange로 입력값을 바꿔주면 된다.

 

auto값을 준 이유는

 - auto값은 안에 내용물이 없으면 기존에 값을 입력받아 생긴 높이값으로 textArea의 height값이 고정이 되기 때문이다.

 

onKeyDown이 아닌 onChange로 한 이유는

 - onKeyDown은 키를 눌러서 값이 변할 때만 실행이 되기때문에 스타일이나 이벤트적으로 살짝 버벅거리는 감이 있다.

그래서 onChange는 값이 바뀌면 이벤트가 발생한다. 

 

다른 블로그들에서는 onKeyDown과 onKeyUp으로 해결 한 사례들이 많았는데, onChange를 안 쓴 이유는 모르겠다.

onChange는 codepen에 참고했다.

 

https://codepen.io/aaroniker/pen/KKdvGGM

 

textarea auto height

...

codepen.io

 

'Javascript > React' 카테고리의 다른 글

http-proxy-middleware로 cors 에러  (0) 2022.08.01
리액트 타입스크립트에서 SVG 사용하기  (0) 2022.07.03