use-visibility-percentage
v1.0.2
Published
A react hook to measure visibility percentage of element on screen
Maintainers
Readme
useVisibilityPercentage
A react hook to measure percentage of element inside the window height (window.innerHeight).
Features
- TypeScript support 🧔
- Lightweight 🐔
Installation
npm i use-visibilty-perctange --saveOr
yarn add use-visibility-percentageUsage
const [percent, position] = useVisibiltyPercentage(ref, \ * { options } * \)| Property | Type | Description | | -------- | --------- | ------------------------------------------------------------- | | ref | react ref | Ref to element you want to monitor | | percent | number | Number between 0 and 1 indicating visible fragment of element | | position | string | One of values ('above', 'top','center', 'bottom', 'below' ) |
Basic usage:
import React from 'react'
import useVisibiltyPercentage from 'use-visibilty-percentage'
const Percent = () => {
const ref = useRef()
const [percent] = useVisibiltyPercentage(ref)
return (
<div
ref={ref}
className='box'
style={{ opacity: percent.toPrecision(2) }}
/>
)
}Using optional options:
import React from 'react'
import useVisibiltyPercentage from 'use-visibilty-percentage'
const Percent = () => {
const ref = useRef()
const [percent] = useVisibiltyPercentage(ref, {
offsetTop: 20,
offsetBottom: 20,
throttle: 30,
})
return (
<div
ref={ref}
className='box'
style={{ opacity: percent.toPrecision(2) }}
/>
)
}Options
Provide these as second argument to hook ( useVisibiltyPerctange(ref, { options }) ).
| Name | Type | Default | Required | Description | | ---------------- | ------ | :-----: | :------: | -------------------------------- | | offsetTop | number | 0 | false | The top offset of window view | | offsetBottom | number | 0 | false | The bottom offset of window view | | throttle | number | 16 | false | The throttle time in miliseconds |
