박철순
React에서 TextArea 자동 높이 조절 본문
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 |