useRef란 리액트의 Hook중 하나로 우리가 평소 DOM을 선택할때 querySelector를 사용한것처럼
react에서는 useRef가 HTML 태그에 접근을 도와준다
import { useRef } from "react";
export default function useRefHook()
const fileRef = useRef(null);
const onClickBtn = () => {
fileRef.current.click();
console.log(fileRef.current)
};
return(
<div>
<button onClick={onClickBtn}>등록하기</button>
<input type="file" ref={fileRef} style={{ display: "none" }}/>
</div>
)
위의 코드에서 console.log를 보면
<input type="file" style="display:none">
위와같이 input태그의 정보를 가져온다
즉 current는 DOM을 가르키고 현재 input에 ref={fileRef}을 통해 fileRef가 인풋태그의 DOM에 접근한것이다
그럼 여기서 fileRef.current.value, fileRef.current.id를 할수 있다는 것이고 현재 코드는 해당 input태그를 클릭하는 것이다
export default function Focus() {
const FocusOn = useRef(null);
useEffect(() => {
FocusOn.current.focus();
}, []);
return <input type="password" ref={FocusOn} />;
}
혹은
export default function useRefSetState() {
const passwordRef = useRef(null);
const [password, setPassword] = useState("")
const onClickSubmit = () => {
setPassword(passwordRef.current.value)
}
return (
<div>
<input type="password" ref={password} />;
<button onClick={onClickSubmit}>제출하기<button>
</div>
)
}
원래라면 onChange를 사용하여 값이 입력될때 마다 setState를 하여 리렌더링이 됬겠지만 위와 같이 작성하면 버튼을 누를때만 리렌더링이 된다