View contents button
Share buttons
How to detect and track Visibility and Scroll progress of a component in React.js?
Posted on 26th Sep, 2021
Last updated a year ago

How do you detect and track the Visibility and Scroll progress of a component in React.js? Say you have to trigger a function only when 50% of it is visible on screen. How would you go about that? If your answer felt complicated, let me show you an easier way.

Say hello to my `react-intersection-revealer`

But we already have react-intersection-observer !

Yup, you do, and it works fantastic. However, I felt that it lacks at something: letting you know what is the amount of visibility of a component. Say, how would you know whether only 75% of the component’s height was visible?

Here’s where react-intersection-revealer steps in. With it, you can know whether a component/element is visible on the viewport currently, and if yes, how much of it is visible.

Getting Started

For us developers, an example is worth more than long documentations when starting out, so here’s a quick example:

1import React, {useRef} from 'react'
2import {useIntersectionRevealer} from 'react-intersection-revealer'
3export default function YourAwesomeComponent(){
4  const ref = useRef()
5  const {heightVisible} = useIntersectionRevealer(ref)
6  return(
7    <>
8      <div className="need-to-track" ref={ref}>...</div>
9      <p>{`${heightVisible}px (height) of the tracked element is on screen`}</p>
10    </>
11  )

Note how I pass the target element’s reference to the useIntersectionRevealer hook, and it returns me the amount by which the target element’s height is visible on the viewport.

Since this is a state, you can use useEffect to invoke some code whenever this changes. In other words, you can effectively track the visibility of any component, and set up breakpoints for code execution.

Here's a demo to show react-intersection-revealer's capabilities.


  • Detect when a component is visible.

  • Detect the amount (absolute and relative) of visibility of a component in the viewport.

  • Detect the amount (absolute and relative) by which a component was scrolled passed by.

  • Location on the viewport (x,y)

These stats, which are just states, get updated on any of these events:

  • Viewport resize (window —onresize)

  • Page scroll (window —onscroll)

  • Target element transition-end (targetElement —ontransitionend)

Read the documentation to know how you can get the package and use these features.

Ending thoughts

This package is fairly new, and I might be adding more features, if I feel the need. Feel free to use it in your projects, and, as always, if you've any ideas or suggestions, I'll be happy to hear them.

About me

Hey there! I am Sohail, and I am a Frontend web developer, specializing in the React.js ecosystem. I love learning, and creating content to help the community.

Have something interesting to say? Hit me up!