use Role
Adds base screen reader props to the reference and floating
elements for a given role
role
.
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 context
context
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 {x, y, strategy, refs, 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={{
position: strategy,
top: y ?? 0,
left: x ?? 0,
}}
{...getFloatingProps()}
>
Floating element
</div>
</>
);
}
function App() {
const {x, y, strategy, refs, 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={{
position: strategy,
top: y ?? 0,
left: x ?? 0,
}}
{...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: true
true
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 isaria-labelledby
aria-labelledby
the group heading.
It’s recommended that you read WAI-ARIA Authoring Practices to ensure your item elements have semantic roles and attributes.