LoginSignup
17
18

More than 3 years have passed since last update.

react-hook-formの基本的な使い方

Posted at

Reactで入力フォームを開発する際に便利なライブラリであるreact-hook-formの基本的な使い方についてまとめておきます。

公式ドキュメントが丁寧に用意されていますので、網羅的に機能を知りたい方はそちらをご覧ください。

実装手順

基本

以下のようなフォームに値を入力させて、submitする想定で改修を加えていきます。

import React from 'react';

function App() {
    return (
        <form>
            <input name="title" />
            <textarea name="content" />
        </form>
    );
}

export default App;

ライブラリのインストール

ライブラリをインストールします。

npm install react-hook-form

or 

yarn add react-hook-form

refの登録

次にライブラリが各フィールドを参照できるよう、registerメソッドをそれぞれのrefに追加します。
TypeScriptの場合は予め、useFormに対して各フィールドを持った型を渡しておきましょう。

import React from 'react';
import { useForm } from 'react-hook-form';

type Post = {
    title: string;
    content: string;
};

function App() {
    const { register } = useForm<Post>();
    return (
        <form>
            <input
                name="title"
                ref={register({ required: true, maxLength: 30 })}
            />
            <textarea name="content" ref={register} />
        </form>
    );
}

export default App;

react-hook-formには基本的なバリデーションも用意されており、このregisterを追加する際に設定することが可能です。

利用できるバリデーションについては以下を参照ください。

バリデーションエラーについて

設定したバリデーションでエラーが発生した場合はreact-hook-formが用意しているerrorオブジェクトを利用してハンドリングすることができます。

import React from 'react';
import { useForm } from 'react-hook-form';

type Post = {
    title: string;
    content: string;
};

function App() {
    const { register, errors } = useForm<Post>();
    return (
        <form>
            <input
                name="title"
                ref={register({ required: true, maxLength: 30 })}
            />
            {errors.title && <span>タイトルは必須です。</span>}
            <textarea name="content" ref={register} />
        </form>
    );
}

export default App;

submit

そして、formタグに対して、コールバックを渡したhandleSubmitを設定します。

import React from 'react';
import { useForm } from 'react-hook-form';

type Post = {
    title: string;
    content: string;
};

function App() {
    const { register, handleSubmit, errors } = useForm<Post>();
    const onSubmit = (data: Post) => {
        console.log(data);
    };
    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <input
                name="title"
                ref={register({ required: true, maxLength: 30 })}
            />
            {errors.title && <span>タイトルは必須です。</span>}
            <textarea name="content" ref={register} />
        </form>
    );
}

export default App;

これでフォームが送信アクションが発生した際に、入力した値がonSubmitに渡されるようになります。

17
18
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
17
18