React-intersection-revealer

Let’s say you are creating a component on ReactJS and you have to trigger a function only when half a percent of it is visible on screen. How will you detect the amount of presence and visibility of a component in ReactJS? We know there is a react-intersection-observer. It lacks something; it fails to let you know what is the amount of visibility of a component. React-intersection-revealer helps you to know whether a component/element is visible on the viewport currently and if it is visible how much of it is visible. 

Example

import React, {useRef} from 'react'

import {useIntersectionRevealer} from 'react-intersection-revealer'


export default function YourAwesomeComponent(){

  const ref = useRef()

  const {heightVisible} = useIntersectionRevealer(ref)


  return(

    <>

      <div className="need-to-track" ref={ref}>...</div>

      <p>{`${heightVisible}px (height) of the tracked element is on screen`}</p>

    </>

  )

}

Take a note on how the target element’s reference is passed to useIntersectionRevealer hook and how it returns the amount by which the element’s height is visible on the viewport. You can set up breakpoints for code execution along with effectively tracking the visibility of components. 

Usage:

There are 9 states provided by this hook. You can hold stats of the target element.

inView- Displays True if element is visible even if it's only partially visible. 

visibleFractionX-Fraction of the element’s width.

visibleFractionY-Fraction of element’s height.

height-Height in pixels.

Width-Width in pixels.

heightVisible-The width of the element’s height which is visible.

widthVisible- The height of the element’s width which is visible.

x-The x coordinate of the element from origin where it’s rendered.

y-The y coordinate of the element from origin where it’s rendered.


These stats get updated on any of the following events listed below.


Viewport resize

Page scroll

Target element transition-end


To track the visibility by percentage pass the reference to the element to be tracked and pass it to useIntersectionRevealer hook.

Here is the github repository link created by Sohail Saha who is a full stack developer.