Skip to content

useRole

Adds base screen reader props to the reference and floating elements for a given rolerole.

import {useRole} from '@floating-ui/react';
import {useRole} from '@floating-ui/react';

Usage

This hook is an interaction hook that returns ARIA attribute props.

To use it, pass it the contextcontext object returned from useFloating()useFloating(), and then feed its result into the useInteractions()useInteractions() array. The returned prop getters are then spread onto the elements for rendering.

function App() {
  const {refs, floatingStyles, context} = useFloating();
 
  const role = useRole(context);
 
  const {getReferenceProps, getFloatingProps} = useInteractions([
    role,
  ]);
 
  return (
    <>
      <div ref={refs.setReference} {...getReferenceProps()}>
        Reference element
      </div>
      <div
        ref={refs.setFloating}
        style={floatingStyles}
        {...getFloatingProps()}
      >
        Floating element
      </div>
    </>
  );
}
function App() {
  const {refs, floatingStyles, context} = useFloating();
 
  const role = useRole(context);
 
  const {getReferenceProps, getFloatingProps} = useInteractions([
    role,
  ]);
 
  return (
    <>
      <div ref={refs.setReference} {...getReferenceProps()}>
        Reference element
      </div>
      <div
        ref={refs.setFloating}
        style={floatingStyles}
        {...getFloatingProps()}
      >
        Floating element
      </div>
    </>
  );
}

Props

interface Props {
  enabled?: boolean;
  role?:
    | 'dialog'
    | 'alertdialog'
    | 'tooltip'
    | 'menu'
    | 'listbox'
    | 'grid'
    | 'tree';
}
interface Props {
  enabled?: boolean;
  role?:
    | 'dialog'
    | 'alertdialog'
    | 'tooltip'
    | 'menu'
    | 'listbox'
    | 'grid'
    | 'tree';
}

enabled

default: truetrue

Conditionally enable/disable the hook.

useRole(context, {
  enabled: false,
});
useRole(context, {
  enabled: false,
});

role

default: 'dialog''dialog'

The role of the floating element.

useRole(context, {
  role: 'tooltip',
});
useRole(context, {
  role: 'tooltip',
});

Item roles

As only the reference and floating element receives these props, you’ll need to provide roles for the items inside the floating element if required.

For instance:

  • A 'menu''menu' role will require the focusable children to have a role of 'menuitem''menuitem', 'menuitemcheckbox''menuitemcheckbox', or 'menuitemradio''menuitemradio'.
  • A 'listbox''listbox' role will require the focusable children to have a role of 'option''option'. If inside a group, then wrapped inside a 'group''group' role that is aria-labelledbyaria-labelledby the group heading.

It’s recommended that you read WAI-ARIA Authoring Practices to ensure your item elements have semantic roles and attributes.