HomeStarbucks Pattern Library

FocusTrap

Notes

Traps keyboard focus in a given element. When opening a dynamically created element, for accessibility we may want to trap keyboard focus in the new element. This is advised for any kind of modal, and may be appropriate for tooltips or components that visually obscure other parts of the UI.

FocusTrap is built into the ModalProvider already.

In addition to trapping keyboard focus, FocusTrap can optionally prevent the body from scrolling via the disableBodyScrollWhenActive prop. This option is in use in the ModalProvider.

Props

  • childrenany

    If not using the 'wrapWithDiv' option, this needs to be a single child element or React Component for FocusTrap to wrap so that focus events are delegated correctly. Make sure your child forwards the ref being passed by this component if not using the wrapWithDiv option.

  • disableBodyScrollWhenActivebool[true]

    For use cases such as a modal where the body should not scroll, set this option to true.

  • enabledbool[true]

    Flag indicating whether FocusTrap should be active (for use cases in which it is always mounted)

  • wrapperDivClassNamestring['']

    If using the wrapWithDiv option, you may need to pass styling to the div that is created. Pass a css className with this prop.

  • wrapWithDivbool[false]

    Flag indicating whether to wrap the children of this component with a div (including focus management props). This is useful when the child of this component ignores extra props.

Example: Setting a Focus Trap!