ref?
- JS๋ฅผ ์ฌ์ฉํ ๋์๋ ํน์ DOM์ ์ ํํด์ผํ๋ ์ํฉ์์ getElementById, querySelector ๊ฐ์ DOM Selector ํจ์๋ฅผ ์ฌ์ฉํด์ DOM์ ์ ํ
- ๋ฆฌ์กํธ๋ฅผ ์ฌ์ฉํ๋ ํ๋ก์ ํธ์์ DOM์ ์ง์ ์ ํํด์ผ ํ๋ ์ํฉ์ด ์๊ธฐ๋ฉด ref๋ฅผ ํ์ฉ
- ํจ์ํ ์ปดํฌ๋ํธ์์ **ref**๋ฅผ ์ฌ์ฉ ํ ๋์๋ **useRef** ๋ผ๋ Hook ํจ์ ์ฌ์ฉ
- ํด๋์ค ์ปดํฌ๋ํธ์์๋ ์ฝ๋ฐฑ ํจ์๋ฅผ ์ฌ์ฉํ๊ฑฐ๋ **React.createRef ๋ผ๋ ํจ์ ์ฌ์ฉ**
- ํฌ์ปค์ค๋ฅผ ์ก์ผ๋ ค๋ฉด nameInput.current.focus() ํํ๋ก ์์ฑ
const nameInput = useReft();
const onClick = () => {
nameInput.current.focus();
}
return(
<input ref={nameInput} />
<button onClick={onClick}>ํด๋ฆญ</button>
)
useRef?
- ๋ฆฌ๋๋๋ง ํ์ง ์๊ณ , ์ปดํฌ๋ํธ์ ์์ฑ๋ง ์กฐํ & ์์
- ์ปดํฌ๋ํธ์ focus๋ฅผ ์์น์ํฌ ํ์ ์๋ ๊ฒฝ์ฐ
- ์์ฑ ๊ฐ์ ์ด๊ธฐํํ ํ์๊ฐ ์๋ ๊ฒฝ์ฐ
- useRef๋ก ์ปดํฌ๋ํธ ์์ ๋ณ์ ๊ด๋ฆฌ
const refContainer = useRef(initialValue)
- useRef๋ .currentํ๋กํผํฐ๋ก ์ ๋ฌ๋ ์ธ์(initialValue)๋ก ์ด๊ธฐํ๋ ๋ณ๊ฒฝ ๊ฐ๋ฅํ ref ๊ฐ์ฒด๋ฅผ ๋ฐํ
- ๋ฐํ๋ ๊ฐ์ฒด๋ ์ปดํฌ๋ํธ์ ์ ์์ ์ฃผ๊ธฐ๋ฅผ ํตํด ์ ์ง
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
- ๋ณธ์ง์ ์ผ๋ก useRef๋ .current ํ๋กํผํฐ์ ๋ณ๊ฒฝ ๊ฐ๋ฅํ ๊ฐ์ ๋ด๊ณ ์๋ “์์”
- useRef๋ ๋ด์ฉ์ด ๋ณ๊ฒฝ๋ ๋ ์๋ ค์ฃผ์ง๋ ์์
- .current ํ๋กํผํฐ๋ฅผ ๋ณํํ๋ ๊ฒ์ด ๋ฆฌ๋ ๋๋ง์ ๋ฐ์์ํค์ง๋ ์์
Reference
Hooks API Reference - React
10. useRef ๋ก ํน์ DOM ์ ํํ๊ธฐ
[React] useRef() ๋ ์ธ์ ์ฌ์ฉํ๋๊ฐ?
๋๊ธ