useLabel

Provides the accessibility implementation for labels and their associated elements. Labels provide context for user inputs.

installyarn add react-aria
version3.36.0
usageimport {useLabel} from 'react-aria'

API#


useLabel( (props: LabelAriaProps )): LabelAria

Example#


The useLabel hook associates a label with a field. It automatically handles creating an id for the field and associates the label with it.

import {useLabel} from 'react-aria';

function ColorField(props) {
  let { labelProps, fieldProps } = useLabel(props);

  return (
    <>
      <label {...labelProps}>{props.label}</label>
      <select {...fieldProps}>
        <option>Indigo</option>
        <option>Maroon</option>
        <option>Chartreuse</option>
      </select>
    </>
  );
}

<ColorField label="Favorite color" />
import {useLabel} from 'react-aria';

function ColorField(props) {
  let { labelProps, fieldProps } = useLabel(props);

  return (
    <>
      <label {...labelProps}>{props.label}</label>
      <select {...fieldProps}>
        <option>Indigo</option>
        <option>Maroon</option>
        <option>Chartreuse</option>
      </select>
    </>
  );
}

<ColorField label="Favorite color" />
import {useLabel} from 'react-aria';

function ColorField(
  props
) {
  let {
    labelProps,
    fieldProps
  } = useLabel(props);

  return (
    <>
      <label
        {...labelProps}
      >
        {props.label}
      </label>
      <select
        {...fieldProps}
      >
        <option>
          Indigo
        </option>
        <option>
          Maroon
        </option>
        <option>
          Chartreuse
        </option>
      </select>
    </>
  );
}

<ColorField label="Favorite color" />

By default, useLabel assumes that the label is a native HTML label element. However, if you are labeling a non-native form element, be sure to use an element other than a <label> and set the labelElementType prop appropriately.

See useRadioGroup and useTextField for examples of how useLabel is used by components.