Skip to content

useElementVisibility

Category
Export Size
1.43 kB
Last Changed
5 days ago

Tracks the visibility of an element within the viewport.

Demo

Usage

tsx
import { 
useElementVisibility
} from '@reause/core'
import {
useRef
} from 'react'
const
target
=
useRef
<HTMLDivElement | null>(null)
const
targetIsVisible
=
useElementVisibility
(
target
)
tsx
const 
target2
=
useRef
<HTMLDivElement | null>(null)
const
target2IsVisible
=
useElementVisibility
(
target2
, {
threshold
: 1.0, // 100% visible
})

rootMargin

If you wish to trigger your callback sooner before the element is fully visible, you can use the rootMargin option (See MDN IntersectionObserver/rootMargin).

ts
const 
targetIsVisible
=
useElementVisibility
(target, {
rootMargin
: '0px 0px 100px 0px',
})

threshold

If you want to control the percentage of the visibility required to update the value, you can use the threshold option (See MDN IntersectionObserver/threshold).

ts
const 
targetIsVisible
=
useElementVisibility
(target, {
threshold
: 1.0, // 100% visible
})

Type Declarations

ts
export interface UseElementVisibilityOptions extends ConfigurableWindow {
    initialValue?: boolean;
    scrollTarget?: ElementTarget | RefObject<Document | null>;
    threshold?: number | number[];
    rootMargin?: string;
    once?: boolean;
}

export type ElementTarget<T extends TargetElement = TargetElement> = RefObject<T | null>

export type ElementTargetOrArray<T extends TargetElement = TargetElement> = ElementTarget<T> | ElementTarget<T>[]

export function useElementVisibility(element: ElementTarget, options?: UseElementVisibilityOptions): boolean

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
c82b0 - fix(core): resolve useIntersectionObserver audit findings (#584)
c75a2 - fix(core): resolve useElementVisibility audit findings (#552)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8