Skip to content

fkrasnowski/useVisibilityPercentage

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

41 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

useVisibilityPercentage

GitHub license code style: prettier

A react hook to measure percentage of element inside the window height (window.innerHeight).

Demonstration Image

Features

  • TypeScript support 🧔
  • Lightweight 🐔

Installation

npm i use-visibilty-perctange --save

Or

yarn add use-visibility-percentage

Usage

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

Releases

No releases published

Packages

No packages published