VisuallyHidden
VisuallyHidden hides its children visually, while keeping content visible to screen readers.
install | yarn add react-aria |
---|---|
version | 3.44.0 |
usage | import {VisuallyHidden} from 'react-aria' |
Introduction#
VisuallyHidden
is a utility component that can be used to hide its children visually, while keeping them visible to screen readers and other assistive technology. This would typically be used when you want to take advantage of the behavior and semantics of a native element like a checkbox or radio button, but replace it with a custom styled element visually.
Props#
Name | Type | Default | Description |
children | ReactNode | — | The content to visually hide. |
elementType | string | JSXElementConstructor<any> | 'div' | The element type for the container. |
isFocusable | boolean | — | Whether the element should become visible on focus, for example skip links. |
id | string | undefined | — | |
style | CSSProperties | undefined | — | |
className | string | undefined | — |
Example#
See useRadioGroup and useCheckbox for examples of using VisuallyHidden
to hide native form elements visually.
Hook#
In order to allow additional rendering flexibility, the useVisuallyHidden
hook can be used in custom components instead of the VisuallyHidden
component. It supports the same options as the component, and returns props to spread onto the element that should be hidden.
useVisuallyHidden( (props: VisuallyHiddenProps )): VisuallyHiddenAria
import {useVisuallyHidden} from 'react-aria'; let { visuallyHiddenProps } = useVisuallyHidden(); <div {...visuallyHiddenProps}>I am hidden</div>
import {useVisuallyHidden} from 'react-aria'; let { visuallyHiddenProps } = useVisuallyHidden(); <div {...visuallyHiddenProps}>I am hidden</div>
import {useVisuallyHidden} from 'react-aria'; let { visuallyHiddenProps } = useVisuallyHidden(); <div {...visuallyHiddenProps} > I am hidden </div>
Gotchas#
VisuallyHidden is positioned absolutely, so it needs a positioned ancestor. Otherwise, it will be positioned relative to the nearest positioned ancestor, which may be the body, causing undesired scroll bars to appear.
<label style={{position: 'relative'}}> <VisuallyHidden> <input type="checkbox" /> </VisuallyHidden> <span>Subscribe to our newsletter</span> </label>
<label style={{position: 'relative'}}> <VisuallyHidden> <input type="checkbox" /> </VisuallyHidden> <span>Subscribe to our newsletter</span> </label>
<label style={{ position: 'relative' }} > <VisuallyHidden> <input type="checkbox" /> </VisuallyHidden> <span> Subscribe to our newsletter </span> </label>