useOpenAndCloseFocus

A utility Hook that focuses an element when a component is first mounted and returns focus to another element when the component unmounts.

useOpenAndCloseFocus is a utility Hook that manages focusing an element when a component is first mounted, and returns focus to an element on the page when that component unmounts.

If no ref is passed to initialFocusRef, the hook focuses the first focusable element inside of the container.

If preventFocusOnOpen prop is passed, then no focus will be applied when component mounts, even if initialFocusRef prop is included. Only initial focus is prevented; focus will still be returned to returnFocusRef when component unmounts.

Usage

useOpenAndCloseFocus settings

NameTypeDefaultDescription
initialFocusRefReact.RefObject<HTMLElement>Optional. The element to focus when the container is mounted on the page.
returnFocusRefReact.RefObject<HTMLElement>Required. The element to focus when the container is unmounted.
containerRefReact.RefObject<HTMLElement>Required. A ref for the containing element.
preventFocusOnOpenReact.RefObject<HTMLElement>Optional. When true, prevents focus when container is mounted.