2
1

More than 1 year has passed since last update.

ReactHooksについてまとめる(Other Hooks useId)

Last updated at Posted at 2022-12-23

概要

ReactHooksのOther Hooksについてのメモ記事です。基本的にReactの公式ドキュメントの咀嚼記事となっています。

今回はuseId編です。

useId

useIdは、アクセシビリティ属性に渡す一意のIDを生成するためのReact Hookです。

リスト内のキーを生成するために useId を呼び出さないでください。キーはあなたのデータから生成されるべきです。

アクセシビリティ属性のためのユニークなIDを生成する

例えば、aria-describebyのような2つのタグが関連していることを示すための属性があります。通常のhtmlでは以下のように指定して使用します。

<label>
  Password:
  <input
    type="password"
    aria-describedby="password-hint"
  />
</label>
<p id="password-hint">
  The password should contain at least 18 characters
</p>

しかし、これをjsxで記述するReactコンポーネントを作成する場合にはハードコードするのは適していません。この際にuseIdを使用してユニークなIDを生成することができ、ハードコードも回避することができます。

import { useId } from 'react';

function PasswordField() {
  const passwordHintId = useId();
  return (
    <>
      <label>
        Password:
        <input
          type="password"
          aria-describedby={passwordHintId}
        />
      </label>
      <p id={passwordHintId}>
        The password should contain at least 18 characters
      </p>
    </>
  );
}

複数の関連する要素のIDを生成する

以下のように複数の関連要素にIDを扶養する必要がある場合には、useIdを呼び出し接頭辞として使用することもできます。

import { useId } from 'react';

export default function Form() {
  const id = useId();
  return (
    <form>
      <label htmlFor={id + '-firstName'}>First Name:</label>
      <input id={id + '-firstName'} type="text" />
      <hr />
      <label htmlFor={id + '-lastName'}>Last Name:</label>
      <input id={id + '-lastName'} type="text" />
    </form>
  );
}

参考

2
1
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
2
1