react 환경에서 <form>
을 쉽게 관리하기 위해 사용하는 모듈
(폼의 상태관리와 유효성 검사를 간단하게 해준다.)
npm install react-hook-form
로 설치 후 사용
모듈 설치 후 사용하고자 하는 페이지나 컴포넌트에서 임포트 후 사용한다.
src > components > Form.jsx 파일
import { useForm } from "react-hook-form"; // 임포트 되는지 확인! export default function Form() { const forms = useForm(); // 호출 console.log(forms); }
console.log(forms)
결과 🔽
handleSubmit(func1[, func2])
: 인자로 두 개의 함수를 받을 수 있다.
func1
: 필수, 유효할 때 실행 (폼 제출이 잘 됐을 때 실행)func2
: 선택, 유효하지 않을 때 실행const onValid = (data) => { console.log("valid", data); // 클라이언트가 작성한 데이터가 객체 형태의 data로 들어옴 // data = {name: "value", ...} // axios 요청 처리 여기서 하면 됨 }; const onInvalid = (data) => { console.log("invalid", data); console.log(data.userName?.message); }; return ( <> <form onSubmit={handleSubmit(onValid, onInvalid)}> ... <button type="submit">제출</button> </form> </> )
이 속성에 의해 onSubmit이 제대로 동작하면
onValid 함수
, 제대로 동작지 않는다면onInvalid 함수
가 실행된다.
{...register("name", {유효성 체크}}
형태로 input
에 name
을 등록하고, validation check
을 할 수 있다.
<input type="text" placeholder="이름(name)" {...register("username", { required: "이름은 필수 항목입니다.", minLength: { value: 2, message: "이름은 필수 항목입니다.", }, })} />
(위 코드에서)
required: true
로 할 경우 값이 입력값 없이 제출하면 안내 문구가 화면에 나타나지 않고,
minLength가 지켜지지 않았을 때만 message가 띄워진다.
input에 입력되는 value를 실시간으로 나타내준다.
/* watch() */ const { register, handleSubmit, watch, formState: { errors }, } = useForm(); console.log("watch username ::", watch("username")); // 🔼 <input {...register("username")} /> 태그의 입력값 감지 console.log("entire info", watch()); // {} 형태 리턴
import {useFrom} from "react-hook-form"; const {formState: {errors}} = useFrom(); return( <> {errors.username?.message} // 아무것도 입력하지 않을 경우 required:"~~" 메시지 띄우고 // 유효성 통과하지 못하면(errors인 경우) message: "~~" 내용을 띄운다. </> )