use-active-element
Tracks the currently focused element (document.activeElement)
Source
Docs
Package
Usage
use-active-element reactively tracks
document.activeElement
– the element that currently has focus. The returned value is updated every time focus moves
to another element:
Focused element: null
Definition
Example: ignore shortcuts while typing
Use the hook to disable global keyboard shortcuts while the user is typing. In the example below, / focuses the search field only when no input is focused:
Press / to focus the search field
Shadow DOM
When focus is inside a web component,
document.activeElement returns the host element. By default, the hook returns the element
that is focused inside the shadow root. Set deep: false to get the host element instead:
Trigger on removal
Focus events are not dispatched when the focused element is removed from the DOM.
By default, the hook uses MutationObserver
to update the value in this case. Set triggerOnRemoval: false to disable it:
TypeScript
The hook accepts a generic type argument for the returned element. It defaults to Element,
narrow it if you know the type of the focused element in advance:
UseActiveElementOptions type is exported from the @mantine/hooks package, you can import it
in your application: