0
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?

TypeScriptとReactで作る型安全なフォームバリデーション【React Hook Formを使った実装】

Posted at
  • 目的
    Reactでフォームバリデーションを実装する際、TypeScriptで型安全を確保しつつ、簡潔にコードを書く方法を解説します。React Hook Formを使い、フォームバリデーションの基本を学びます。

  • 開発環境
    React 17.x

TypeScript

React Hook Form 7.x

  1. React Hook Formのインストール
    bash
    Copy
    Edit
    npm install react-hook-form
  2. 型安全なフォームの作成
    TypeScriptの型を使ってフォームデータの型を定義します。

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

interface FormData {
username: string;
email: string;
}

const MyForm = () => {
const { register, handleSubmit, formState: { errors } } = useForm();

const onSubmit = (data: FormData) => {
console.log(data);
};

return (



{errors.username &&

{errors.username.message}

}
  <input {...register('email', { required: 'Email is required' })} />
  {errors.email && <p>{errors.email.message}</p>}

  <button type="submit">Submit</button>
</form>

);
};

-まとめ
TypeScriptとReact Hook Formを使うことで、型安全でバリデーションが簡潔なフォームを作成できます。React Hook Formはフォームの状態管理を簡単にしてくれるため、効率的にバリデーションを実装できます。

0
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
0
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?