반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

autosize 본문

리액트

autosize

5_hyun 2022. 12. 20. 02:08

autosize

공식 페이지

https://www.npmjs.com/package/autosize

 

autosize

Autosize is a small, stand-alone script to automatically adjust textarea height to fit text.. Latest version: 5.0.2, last published: a month ago. Start using autosize in your project by running `npm i autosize`. There are 541 other projects in the npm regi

www.npmjs.com

autosize는 DT라서 TypeScript에서는 TD까지 같이 설치해야된다.

설명

textarea

autosize는 textarea 태그에서 사용할 수 있다. 

글의 내용이 많아지게 되면 height를 autosize가 알아서 늘려주는 역할을 한다.

코드

import autosize from "autosize";

// ...

const ref = useRef<HTMLTextAreaElement>(null);

useEffect(() => {
if (ref) {
  autosize(ref.current as HTMLTextAreaElement);
}
}, []);

// ...

return(
    <textarea
      ref={ref}
      value={explain}
      onChange={onChangeInformation}
      placeholder={"상품 설명을 입력해주세요."}
    />
);

1. ref에 useRef<HTMLTextAreaElement>(null)을 넣는다.

2. useEffect의 dependency array에 빈 배열을 넣으면 리렌더 될 때 마다 ref가 있는 태그를 체크해준다. 여기서 as HTMLTextAreaElement로 강제 타입 지정을 해야 에러가 안났다.(as로 강제 타입 지정을 하는 것은 타입에 정말 확신이 있을 때만 사용하는 것이 좋다.)

3. 사용할 textarea의 ref에 위에서 선언한 ref를 넣으면된다.

728x90
반응형
Comments