Skip to content

useActiveElement

Category
Export Size
545 B
Last Changed
5 days ago

Reactive document.activeElement

Demo

Usage

tsx
import { 
useActiveElement
} from '@reause/core'
const
activeElement
=
useActiveElement
()
// React keyed on the element — re-runs when focus moves
useEffect
(() => {
console
.
log
('focus changed to',
activeElement
)
}, [
activeElement
])

Options

OptionTypeDefaultDescription
deepbooleantrueTraverse into open shadow roots to find the deeply active element
triggerOnRemovalbooleanfalseRe-read the active element when the tracked element is removed from the DOM (MutationObserver)
documentDocument | ShadowRootthe resolved window's documentCustom Document or open ShadowRoot to read activeElement from — e.g. a shadow root or an iframe
windowWindowthe global window on the clientCustom Window instance — e.g. an iframe's window or a testing environment

Shadow DOM Support

By default, useActiveElement will traverse into shadow DOM to find the deeply active element. Set deep: false to disable this behavior.

tsx
import { 
useActiveElement
} from '@reause/core'
// Only get the shadow host, not the element inside shadow DOM const
activeElement
=
useActiveElement
({
deep
: false })

Track Element Removal

Set triggerOnRemoval: true to update the active element when the currently active element is removed from the DOM. This uses a MutationObserver under the hood.

tsx
import { 
useActiveElement
} from '@reause/core'
const
activeElement
=
useActiveElement
({
triggerOnRemoval
: true })

Custom document / window

Read activeElement from a different root than the global document — an open shadow root, an iframe's document, or a test environment. document wins when both are given; otherwise it falls back to the resolved window's document. The blur / focus / pointerdown listeners are always bound to the resolved window.

tsx
import { 
useActiveElement
} from '@reause/core'
// Read from an open shadow root instead of document const
activeElement
=
useActiveElement
({
document
: shadowRoot })
// Read from another window (its document is used when `document` is omitted) const
activeElementInFrame
=
useActiveElement
({
window
: iframe.contentWindow })

Type Declarations

ts
export interface UseActiveElementOptions extends ConfigurableWindow {
    document?: Document | ShadowRoot;
    deep?: boolean;
    triggerOnRemoval?: boolean;
}

export function useActiveElement<T extends HTMLElement = HTMLElement>(options?: UseActiveElementOptions): T | undefined

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
c1971 - fix(core): resolve useActiveElement audit findings (#516)
b3499 - feat(core): add useActiveElement (#63)

Released under the MIT License. v0.1.8