</> ErrorMessage:
コンポーネント
関連付けられた入力のエラーメッセージを表示するシンプルなコンポーネント。
npm install @hookform/error-message
プロパティ
名前 | 型 | 必須 | 説明 |
---|---|---|---|
name | 文字列 | ✓ | フィールドの名前。 |
errors | オブジェクト | React Hook Formからのerrors オブジェクト。FormProvider を使用している場合はオプションです。 | |
message | 文字列 | React.ReactElement | インラインエラーメッセージ。 | |
as | React.ElementType | 文字列 | ラッパーコンポーネントまたはHTMLタグ。例:as="span" またはas={ | |
render | ({ message: string | React.ReactElement, messages?: Object}) => any | これは、エラーメッセージまたはメッセージをレンダリングするためのレンダープロップです。 注記: messages を使用するには、criteriaMode を'all'に設定する必要があります。 |
例
単一エラーメッセージ
import React from "react"import { useForm } from "react-hook-form"import { ErrorMessage } from "@hookform/error-message"interface FormInputs {singleErrorInput: string}export default function App() {const {register,formState: { errors },handleSubmit,} = useForm<FormInputs>()const onSubmit = (data: FormInputs) => console.log(data)return (<form onSubmit={handleSubmit(onSubmit)}><input{...register("singleErrorInput", { required: "This is required." })}/><ErrorMessage errors={errors} name="singleErrorInput" /><ErrorMessageerrors={errors}name="singleErrorInput"render={({ message }) => <p>{message}</p>}/><input type="submit" /></form>)}
複数エラーメッセージ
import React from "react"import { useForm } from "react-hook-form"import { ErrorMessage } from "@hookform/error-message"interface FormInputs {multipleErrorInput: string}export default function App() {const {register,formState: { errors },handleSubmit,} = useForm<FormInputs>({criteriaMode: "all",})const onSubmit = (data: FormInputs) => console.log(data)return (<form onSubmit={handleSubmit(onSubmit)}><input{...register("multipleErrorInput", {required: "This is required.",pattern: {value: /d+/,message: "This input is number only.",},maxLength: {value: 10,message: "This input exceed maxLength.",},})}/><ErrorMessageerrors={errors}name="multipleErrorInput"render={({ messages }) =>messages &&Object.entries(messages).map(([type, message]) => (<p key={type}>{message}</p>))}/><input type="submit" /></form>)}
ご支援ありがとうございます
React Hook Formがプロジェクトで役立つと感じた場合は、スターを付けてサポートをご検討ください。