読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第3節 まちがいを表示する

3.2 入力欄のそばに表示する

まちがいの表示を、1つの部品にまとめます。

// src/components/FormField.tsx
type FormFieldProps = {
  id: string;
  label: string;
  error?: string[] | undefined;
  children: (props: { "aria-invalid": boolean; "aria-describedby": string | undefined }) => React.ReactNode;
};

export const FormField = ({ id, label, error, children }: FormFieldProps) => {
  const errorId = `${id}-error`;
  const hasError = error !== undefined && error.length > 0;
  return (
    <div className="form-field">
      <label htmlFor={id}>{label}</label>
      {children({ "aria-invalid": hasError, "aria-describedby": hasError ? errorId : undefined })}
      {hasError && (
        <p id={errorId} className="form-error">
          {error[0]}
        </p>
      )}
    </div>
  );
};
<FormField id="name" label="お名前" error={state.fieldErrors?.name}>
  {(aria) => <input id="name" name="name" defaultValue={state.values?.name ?? ""} {...aria} />}
</FormField>
属性意味
aria-invalidこの欄の値がまちがっていることを、読み上げの道具に伝える
aria-describedbyまちがいの文を、この欄の説明として結び付ける

色だけでまちがいを示すと、色の見分けにくい人には伝わりません。文で書き、欄と結び付けます。

解答の例

&lt;FormField id=&quot;phone&quot; label=&quot;電話番号&quot; error={state.fieldErrors?.phone}&gt;{(aria) => &lt;input id=&quot;phone&quot; name=&quot;phone&quot; type=&quot;tel&quot; defaultValue={state.values?.phone ?? &quot;&quot;} {...aria} /&gt;}&lt;/FormField&gt; と書きます。

11 / 16