NextJS,react-hook-form 로그인폼 구현

강민혁·2022년 10월 12일
0
코드를 입import { useForm } from 'react-hook-form';

export default function LoginForm() {
    type HookFormTypes = {
        id: string;
        pw: string;
    }
    const { register, watch, handleSubmit, formState: { errors } } = useForm<HookFormTypes>();
    console.log(watch());
    return (
        <form onSubmit={
            handleSubmit(async (loginData) => await console.log(loginData))
        }>
            <input
                {...register("id", {
                    required: true,
                    minLength: {
                        value: 8,
                        message: "아이디는 최소 8자 이상으로 입력하세요 !!"
                    },
                })}
                type="text"
                placeholder="ID"
            />
            <span>
                {errors.id?.type === "required" && "아이디는 필수입니다"}
                {errors.id?.type === "minLength" && errors.id.message}
            </span>
            <input
                {...register("pw", {
                    required: true,
                    minLength: {
                        value: 8,
                        message: "비밀번호는 최소 8자 이상으로 입력하세요 !!"
                    },
                    maxLength: {
                        value: 20,
                        message: "20자 이하로 입력하세요 !!"
                    }
                })}
                type="password"
                placeholder="PW"
            />
            <span>
                {errors.pw?.type === "required" && "비밀번호는 필수입니다"}
                {errors.pw?.type === "minLength" && errors.pw.message}
            </span>
            <input type="submit" />
        </form>
    )
}

간단하게 로그인폼 구현하기
useForm을 이용해 react-hook-form 라이브러리에있는 함수들을 가져와서 쓸수있다!

watch : 입력값이 변경될때마다 콘솔에 출력
handelSubmit : form태그 submit시 값 추출
formState : 폼의상태 확인후 값에따라 errormessage 출력

profile
화이팅

0개의 댓글