react-hook-form, yup

NOAH·2021년 7월 11일
0
post-thumbnail

yup react-hook-form에서 사용

npm i @hookform/resolvers

재사용 가능한 react-hook-form

component

import { ReactNode } from 'react';
import { TextField } from '@material-ui/core';
import { Controller, useFormContext } from 'react-hook-form';

export default function SignupComponent(): ReactNode {
  const {
    register,
    control,
    handleSubmit,
    watch,
    formState: { errors },
  } = useFormContext();

  return (
    <>
      <Controller
        name="email"
        control={control}
        defaultValue=""
        render={({ field }) => (
          <TextField
            {...field}
            type="email"
            label="Email"
            variant="outlined"
            error={!!errors.email}
            helperText={errors.email ? errors.email?.message : ''}
          />
        )}
      />
      <br />
      <br />
      <Controller
        name="password"
        control={control}
        render={({ field }) => (
          <TextField
            {...field}
            type="password"
            label="Password"
            variant="outlined"
            error={!!errors.password}
            helperText={errors.password ? errors.password?.message : ''}
          />
        )}
      />
    </>
  );
}
  • register: input 이름 등록
  • handleSubmit: form onSubmit 이벤트 핸들러
  • watch: watch("input 이름")하면 onChange와 같은 역할을 함
  • formState: { errors }: error의 종류에 따라 각기 다른 error가 객체형태로 저장이 됨, ex) 형식, 길이제한 등
  • Controller: UI 라이브러리를 react-hook-form에서 사용 할 수 있도록 해주는 wrapper

form

import { ReactNode } from 'react';
import { yupResolver } from '@hookform/resolvers/yup';
import Head from 'next/head';
import { useForm, SubmitHandler, FormProvider } from 'react-hook-form';
import * as yup from 'yup';
import SignupComponent from '@components/signupComponent';

interface IFormInputs {
  email: string;
  password: string;
}

const schema = yup.object().shape({
  email: yup.string().email().required(),
  password: yup.string().min(12).max(32).required(),
});

export default function Signup(): ReactNode {
  const methods = useForm<IFormInputs>({
    resolver: yupResolver(schema),
  });

  const onSubmit: SubmitHandler<IFormInputs> = (data) => {
    console.log('form data', data);
  };

  return (
    <>
      <Head>
        <title>회원가입 - 인프런 | 온라인 강의 플랫폼</title>
      </Head>
      <main>
        <FormProvider {...methods}>
          <form onSubmit={methods.handleSubmit(onSubmit)}>
            <SignupComponent />
            <input type="submit" />
          </form>
        </FormProvider>
      </main>
    </>
  );
}
profile
Steady Web Developer

0개의 댓글