๊ฑฐ์ ์ค๋ ํ๋ฃจ ์ข
์ผ ๋ ๋ ธ๋ค๊ณ ํด๋ ๊ณผ์ธ์ด ์๋๋ฐ ์๋ ์ฝ๋๊ฐ ์ด ์ง์ฅ์์ ๋ ๊ตฌ์ถํด ๋๋ค ...๋ฐํํ
์ค๋ ๋ด๋ด ํ์จ ํนํน ์ฌ๋ฉฐ ๊ตฌ๊ธ๋งํ๋๋ฐ ์๊ฐ๋ณด๋ค ๋ต์ ๊ฐ๊น์ด ๊ณณ์ ์์๋ค.
๊ทธ๋ฆฌ๊ณ ์ค๋์ ํตํด ๊นจ๋ฌ์ ๋ฐ, '์ธ์ ๊ฐ ๋์ ์จ๋ค.'
๊ฐ์คํ๊ณ ,
๋ฆฌ์กํธ์์ textarea ๋์ด๋ฅผ ์๋์ผ๋ก ์กฐ์ ํด๋ณด์!
//์๋ต
const textRef = useRef();
const autoResizeTextarea = useCallback(() => {
textRef.current.style.height = "auto";
textRef.current.style.height = textRef.current.scrollHeight + "px";
}, []);
return (
//์๋ต
<textarea
className="tweetSender__writeBox__text__textarea"
type="text"
wrap="on"
placeholder="๋ฌด์จ ์ผ์ด ์ผ์ด๋๊ณ ์๋์?"
maxLength={150}
value={tweet}
onChange={onChange}
ref={textRef}
onInput={autoResizeTextarea}
/>
)
.tweetSender__writeBox__text__textarea {
cursor: text;
line-height: 24px;
pointer-events: auto;
width: 100%;
display: block;
resize: none;
overflow-y: hidden;
background-color: black;
color: white;
min-height: 52px;
white-space: pre-wrap;
overflow-wrap: break-word;
height: auto;
&::placeholder {
font-size: inherit;
}
const textRef = useRef();
textarea ์๋ฆฌ๋จผํธ์ ์ง์ ์ ๊ทผํ๊ธฐ ์ํด useRef() ํ
์ ์ฌ์ฉํ์!
textarea ์ฐฝ์ useRef ํ
์ ์ด์ฉํด textRef๋ก ์ง์ DOM์ ์ค์ ํ๋ค.
- useRef()
: current ์์ฑ์ ๊ฐ์ง๋ ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ Hook์ด๋ค.
- ์ธ์๋ก ๋์ด์จ ์ด๊ธฐ ๊ฐ์ current ์์ฑ์ ํ ๋นํ๋ค.
- current์ ์์ฑ์ ๊ฐ์ ๋ณ๊ฒฝํด๋ ์ํ๋ฅผ ๋ณ๊ฒฝํ ๋ ์ฒ๋ผ ๋ฆฌ์กํธ ์ปดํฌ๋ํธ๊ฐ ๋ฆฌ๋๋๋ง ๋์ง๋ ์๋๋ค. ์ฆ, ๋ฆฌ๋๋๋ง ๋๋๋ผ๋ current์ ์์ฑ๊ฐ์ ์ง์๋๋ค.
- useRef()๋ ๋ณดํต DOM ๋ ธ๋๋ React ์๋ฆฌ๋จผํธ์ ์ง์ ์ ๊ทผํ ๋ ์ฌ์ฉํ๋ค.
- Ref๊ฐ์ฒด์ .current ๊ฐ์ ์ ํํ DOM์ ๊ฐ๋ฆฌํจ๋ค.
์ฌ๊ธฐ์textRef.current๋ textarea ์๋ฆฌ๋จผํธ๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
๋ฐ๋ผ์textRef.current.style.height์ textarea ์๋ฆฌ๋จผํธ์ height ๊ฐ์ ๊ฐ๋ฆฌํค๊ณtextRef.current.scrollHeight์ textarea ์๋ฆฌ๋จผํธ์ ์ ์ฒด scrollHeight๊ฐ์ ๊ฐ๋ฆฌํจ๋ค.
onInput={autoResizeTextarea}
textarea์ input๋ ๋๋ง๋ค, ์ฆ ๊ธ์ด ์
๋ ฅ๋ ๋ ๋ง๋ค autoResizeTextarea ํจ์๋ฅผ ํธ์ถํ๋ค.
useCallback()
useCallback๋ก autoResizeTextarea ํจ์๋ฅผ ๊ฐ์ธ์ ํจ์๋ฅผ ์ฌ์ฌ์ฉํ ์ ์๊ฒ ํ์.
- useCallback(ํจ์, [๋ฐฐ์ด])
: ํน์ ํจ์๋ฅผ ์ฌ์ฌ์ฉํ๊ณ ์ถ์ ๋ ์ฌ์ฉํ๋ Hook์ด๋ค.
- useCallback์ ์ฒซ๋ฒ์งธ ์ธ์๋ก ๋์ด์จ ํจ์๋ฅผ ๋๋ฒ์งธ ์ธ์๋ก ๋์ด์จ ๋ฐฐ์ด ๋ด์ ๊ฐ์ด ๋ณ๊ฒฝ๋ ๋๊น์ง ์ ์ฅํด๋๊ณ ์ฌ์ฌ์ฉํ ์ ์๊ฒํ๋ค.
- useCallback()์ ์ฌ์ฉํ๋ฉด, ํด๋น ์ปดํฌ๋ํธ๊ฐ ๋๋๋ง๋๋๋ผ๋ ๊ทธ ํจ์๊ฐ ์์กดํ๋ ๊ฐ๋ค์ด ๋ฐ๋์ง ์๋ ํ ๊ธฐ์กด ํจ์๋ฅผ ๊ณ์ํด์ ๋ฐํํ๋ค.
์ฆ, ์ฌ๊ธฐ์๋ autoResizeTextarea ์ปดํฌ๋ํธ๊ฐ ๋๋๋ง๋๋๋ผ๋ textarea์ ๋์ด๊ฐ ๋ฐ๋์ง ์๋ ํ ๊ธฐ์กด ํจ์๋ฅผ ๊ณ์ํด์ ๋ฐํํ๋ค.
- (๐ ์ฐธ๊ณ ) ๋ฆฌ์กํธ๊ฐ ๋ฆฌ๋๋๋ง ํ๋ ์กฐ๊ฑด
- ์์ ์ state ๋ณ๊ฒฝ๋ ๋
- ๋ถ๋ชจ ์ปดํฌ๋ํธ๋ก๋ถํฐ ์ ๋ฌ ๋ฐ์ props๊ฐ ๋ณ๊ฒฝ๋ ๋
- ๋ถ๋ชจ ์ปดํฌ๋ํธ๊ฐ ๋ฆฌ๋๋๋ง๋ ๋
textRef.current.style.height = "auto";
textarea์ height์ "auto"๋ก ๋ฐ๊ฟ์ค๋ค.
height ๊ฐ์ auto๋ก ์
๋ ฅํด ๋์ผ๋ฉด textarea์ ์ ์ ๊ธ์ ์ง์ ์ ๋ ๋์ด๋ textarea์ ๋์ด๊ฐ auto๋ก ๋ฐ๋์ด ์๋ง์ ๋์ด๋ก ์ค์ด๋ ๋ค.
textRef.current.style.height = textRef.current.scrollHeight + "px";
textarea์ height์ textarea์ scrollHeight ๋์ด๋ฅผ ๋ฃ์ด์ค๋ค.
textarea์ ์
๋ ฅํ ๊ธ์ด textarea์ ๋์ด๋ฅผ ์ด๊ณผํ ๊ฒฝ์ฐ, textarea์ ๋์ด๊ฐ ์๋์ผ๋ก scrollHeight ๋์ด๋งํผ ๋์ด๋๊ฒ ๋์ด textarea์ ๋์ด๊ฐ ์๋์ผ๋ก ์กฐ์ ๋๋ ๋๋์ ์ค ์ ์๋ค.