React
[React] useRef
J3SUNG
2021. 1. 8. 16:49
728x90
useRef는 자바스크립에서 getElementById()를 하는것과 같은 기능입니다.
아래 예제에서는 input에 2초후에 focus가 가도록 하는 코드입니다.
사용할 태그내에서 ref={ }를 사용해서 useRef()를 통해 받은 값을 넣습니다.
그리고 그 값을 이용해서 해당 태그에 접근할 수 있습니다.
import React, {useRef} from "react";
const App = () => {
const input = useRef();
setTimeout(() => input.current.focus(), 2000);
return (
<input ref={input} />
)
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);