useTextField

Provides the behavior and accessibility implementation for a text field.

installyarn add @react-aria/textfield
version3.0.0-rc.2
usageimport {useTextField} from '@react-aria/textfield'

API#


useTextField(props: TextFieldAriaProps, ref: RefObject<HTMLInputElement>): TextFieldAria

Features#


Text fields can be built with <input> and <label> elements, but you must manually ensure that they are semantically connected via ids for accessibility. useTextField helps automate this, and handle other accessibility features while allowing for custom styling.

Anatomy#


Text fields consist of an input element and a label. useTextField automatically manages the relationship between the two elements using the for attribute on the <label> element and the aria-labelledby attribute on the <input> element.

useTextField returns two sets of props that you should spread onto the appropriate element:

NameTypeDescription
inputPropsInputHTMLAttributes<HTMLInputElement & HTMLTextAreaElement>Props for the input element.
labelPropsLabelHTMLAttributes<HTMLLabelElement>Props for the text field's visible label element (if any).

If there is no visual label, an aria-label or aria-labelledby prop must be passed instead to identify the element to screen readers.

Example#


function TextField(props) {
  let {label} = props;
  let ref = React.useRef();
  let {labelProps, inputProps} = useTextField(props, ref);

  return (
    <div style={{display: 'flex', flexDirection: 'column', width: 200}}>
      <label {...labelProps}>{label}</label>
      <input {...inputProps} ref={ref} />
    </div>
  );
}

<TextField 
  label="Email"
  placeholder="abc@example.com" />

Internationalization#


RTL#

In right-to-left languages, text fields should be mirrored. The label should be right aligned, along with the text in the text field. Ensure that your CSS accounts for this.