바닐라 JS에서 줄기차게썼던, querySelector 와 비슷한 역할을 해주는 Hook이다. 아래는 회원가입하는 폼인데, emailRef, passwordRef를 useRef로 생성하고, 특정 요소의 ref 속성에 할당하여emailRef.current.value 이렇게 값을 읽어오는 방식이다.
import { useRef } from "react";
export default function RegisterForm({ onSubmit }) {
const emailRef = useRef();
const passwordRef = useRef();
const submitForm = (e) => {
e.preventDefault();
const email = emailRef.current.value;
const password = passwordRef.current.value;
const formData = {
email,
password,
};
onSubmit(formData);
};
return (
<div>
<form>
<fieldset>
<label htmlFor="email">Email</label>
<input
required
ref={emailRef}
id="email"
type="email"
name="email"
autoComplete="off"
/>
</fieldset>
<fieldset>
<label htmlFor="password">Password</label>
<input
required
ref={passwordRef}
id="password"
type="password"
name="password"
placeholder="Enter password"
/>
</fieldset>
<button onClick={submitForm}>Reigster</button>
</form>
</div>
);
}
벨로퍼트님 블로그에도 잘 나와있다. https://react.vlpt.us/basic/10-useRef.html