4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Formik + TypeScriptでフォームを実装してみる

Posted at

Formikとは

  • Reactのフォーム実装は複雑になりがちなので、それをシンプルに実装できるようにしたライブラリ。

Formikを使わない実装と使った実装で比較

  • 入力された値をalert()で表示するフォームを実装
  • 言語はTypeScript

純粋なReactのみで実装したフォームの実装コード


const PureForm: React.FC = () => {
    const [value, setValue] = useState<PostValues>({ text: "" });

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
        alert(value.text + "が入力されました!");
        event.preventDefault();
    };
    const handleChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
        setValue({ text: event.target.value });
    };

    return (
        <form onSubmit={e => handleSubmit(e)}>
            <input type="text" name="text" onChange={e => handleChange(e)} />
            <button type="submit">送信</button>
        </form>
    );
};

Formikを使ったフォームの実装コード


const FormikForm: React.FC = () => {
    return (
        <Formik
            initialValues={{ text: "" }}
            onSubmit={(values: PostValues, actions: FormikActions<PostValues>) => {
                actions.resetForm();
                alert(values.text + "が入力されました!");
            }}
            render={() => (
                <Form>
                    <Field type="text" name="text" />
                    <button type="submit">送信</button>
                </Form>
            )}
        />
    );
};
  • まず、コンポーネント内で明示的にフォームのstateを管理する必要が無くなるのが大きい。
  • TypeScriptで実装しようとするとeventの型を定義してあげる必要があり、React.FormEvent<T>React.ChangeEvent<T>といったような普段あまり意識しないような型を定義してあげる必要がある。
    • 公式チュートリアル(JavaScriptで書かれている)で勉強しているときに型が分からず見事にハマった。 any型で回避
  • render()の中で使っているFormと[Field]
    (https://jaredpalmer.com/formik/docs/api/field)タグはFormikで用意されているもの。

Formikを使ってみた所感

  • Reactのフォームのクセが上手くラップされていて使い勝手が良かった。
  • ライブラリを用いずバリデーションをかけようとするとかなり大変そうだったが、Yupと組み合わせる事でシンプルにバリデーションを実装できるのがありがたかった。(今回のコードではバリデーションは未実装。)
  • 学習コストはそれほど高くないように感じたのでフォームの実装で苦労している場合は導入してみると良いかなと感じた。

参考

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?