A react hook to measure percentage of element inside the window height (window.innerHeight).
- TypeScript support 🧔
- Lightweight 🐔
npm i use-visibilty-perctange --save
Or
yarn add use-visibility-percentage
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) }}
/>
)
}
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 |