🎃

【Web Library】Nextjs13で覚える便利なライブラリ【#9Formik Props】

2023/03/04に公開

【#9Formik Props】

YouTube: https://youtu.be/Qcui18WWsC0

https://youtu.be/Qcui18WWsC0

今回は「Formik」コンポーネントのpropsの中身を見ていきます。

https://formik.org/docs/overview

「Formik」コンポーネントのpropsで
「initialValues」「validate」「onSubmit」の設定を行います。

app/formik/basic/page.tsx
'use client';
import { Formik, Form, Field, ErrorMessage, FormikErrors } from 'formik';

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

const Page = () => {
  return (
    <div className="text-white">
      <h1 className="mb-4 text-center text-3xl font-bold">
        Any place in your app!
      </h1>
      <Formik
        initialValues={{ email: '', password: '' }}
        validate={(values) => {
          const errors: FormikErrors<FormikValues> = {};

          if (!values.email) {
            errors.email = 'Required';
          } else if (
            !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
          ) {
            errors.email = 'Invalid email address';
          }

          if (!values.password) {
            errors.password = 'Password Required';
          } else if (values.password.length < 8) {
            errors.password = 'パスワードは8文字以上を設定してください';
          }

          return errors;
        }}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));

            setSubmitting(false);
          }, 400);
        }}
      >
        {({ isSubmitting }) => (
          <Form className="flex flex-col items-center gap-3">
            <Field type="email" name="email" className="text-gray-900" />
            <ErrorMessage
              name="email"
              component="div"
              className="text-red-500"
            />
            <Field type="password" name="password" className="text-gray-900" />
            <ErrorMessage
              name="password"
              component="div"
              className="text-red-500"
            />
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </Form>
        )}
      </Formik>
    </div>
  );
};

export default Page;

Discussion