1.0.3 • Published 5 years ago

react-visibility-tracking-hooks v1.0.3

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

React Visibility Tracking Hooks

React Hooks for tracking visibility status of elements in viewport, inspired by react-visibility-sensor

Installation

using npm

npm install react-visibility-tracking-hooks

or with yarn

yarn add react-visibility-tracking-hooks

Example

You can find an example here

or if you want to run it locally, clone this project and then:

 cd example
 npm install
 npm start

Usage

import useVisibilityTracking from "react-visibility-tracking-hooks"

function onVisibilityChange (isVisible, percentVisible) {
  console.log(`Element is visible ?: ${isVisible}`);
  console.log(`Visibility Percent - horizontal: ${percentVisible.horizontalPercent} - vertical: ${percentVisible.verticalPercent} - overall: ${percentVisible.overallPercent}`);
}

function MyComponent() {
  const [ref, { rect, isVisible, percentVisible }] = useVisibilityTracking({
    onVisibilityChange: onVisibilityChange,
    partiallyVisible: false,
    scrollCheck: true,
    scrollThrottleLimit: 250,
    resizeCheck: false,
    resizeThrottleLimit: 250,
    minElementOffset: {
      top: 0,
      left: 0,
      bottom: 0,
      right: 0
    },
  })

  return (
    <div ref={ref}>
      This element will be tracked !!
    </div>
  )
}

Options

OptionDescriptionDefault
onVisibilityChangecallback for whenever the element visibility status changes (every window "scroll" or "resize")undefined
partiallyVisibleIf true, consider element visible even when only a part of it is visible. The value can also be 'top', 'left', 'bottom', or 'right' in case we want to specifically consider only one part of the element as visiblefalse
scrollCheckIf true, "scroll" event listener will be enabledtrue
scrollThrottleLimitThrottle delay for "scroll" event250
resizeCheckIf true, "resize" event listener will be enabledfalse
resizeThrottleLimitThrottle delay for "resize" event250
minElementOffsetOffset padding (in px) for each side of element, positive value will padded inside element (rectangle will be smaller) and vice versa for negative value{ top: 0, left: 0, bottom: 0, right: 0 }

Utility

  • checkIsVisible(nodeRect, containmentRect, minElementOffset, partiallyVisible): Function for checking if nodeRect is visible inside containmentRect
  • computePercentVisible(nodeRect, containmentRect): Function to compute how much (in percent) nodeRect is inside containmentRect

Note:

  • nodeRect and containmentRect need to be in this format
    // position relative to window viewport (px)
    { 
      top: 0, 
      left: 0, 
      bottom: 0, 
      ight: 0 
    }

TO-DO

License

MIT