๋ฌธ์ ์ํฉ
ํธ์ํฐ ํด๋ก ์ฝ๋ฉ ์ค ํฌ์คํธ๋ฅผ ์์ฑํ๋ textarea์ ์ ๋ ฅํ ํ ์คํธ์์ด ๋ง์์ง๋ฉด ๋ณด๊ธฐ ์ซ์ ์คํฌ๋กค๋ฐ๊ฐ ์๊ธฐ๋ ๊ฒ์ ํ์ธํ๋ค. ๋จ์ํ ์คํฌ๋กค๋ฐ๋ฅผ ์ปค์คํ ํด๋ ๋์ง๋ง, ์ค์ ํธ์ํฐ์์๋ ํ ์คํธ์์ ๋ฐ๋ผ ์ ๋ ฅ์นธ์ ๋์ด๊ฐ ์๋์ผ๋ก ๋์ด๋๋๋ก ํ๊ณ ์๊ธฐ ๋๋ฌธ์ ์ด๋ฅผ ์ ์ฉํด๋ณด๊ธฐ๋ก ํ๋ค.
ํด๊ฒฐ ๋ฐฉ๋ฒ
1. useRef ๋ฆฌ์กํธํ ์ ํตํด ๋์ด๋ฅผ ์กฐ์ ํ textarea DOM ์์์ ์ ๊ทผํ๋ค.
2. textarea ์์์ ์ ๋ ฅ์ด ๋ฐ์ํ ๋๋ง๋ค, ํด๋น ์์์ scrollHeight๋งํผ height๋ฅผ ์ค์ ํด์ค๋ค.
์์ค์ฝ๋
import { useRef, useState } from "react"; // useRef ๋ฆฌ์กํธ ํ
์ฌ์ฉ
export default function PostTweetForm() {
const [post, setPost] = useState("");
// 1. useRef ํ
์ ์ฌ์ฉํ์ฌ ๋์ด๋ฅผ ์กฐ์ ํ textarea ์์ ์ ๊ทผ
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
// 2. textarea ์์์ ์
๋ ฅ์ด ์ผ์ด๋ ๋ ์คํํ ํจ์
const onChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setPost(e.target.value);
// ์ ๊ทผํ textareaRef๊ฐ ์์ผ๋ฉด, height๋ฅผ ํด๋น ์์์ scrollHeight๋ก ์ค์
if (textareaRef && textareaRef.current) {
textareaRef.current.style.height = "auto";
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
};
return (
<>
<textarea
ref={textareaRef} // ๋์ด๋ฅผ ๋ณ๊ฒฝํ textarea์ ์ ๊ทผ
onChange={onChange}
value={post}
/>
</>
);
}
๊ฒฐ๊ณผ
728x90