How to use React visibility sensor
Blog React React Visibility Sensor

In this post you will learn how to use react visibility senor. If you manually try to achieve a functionality which gonna detect when a component is coming into viewport. That will be too confusing because in that functionality you need to add a scroll listener and need to calculate component size etc. Which maybe not a good idea. The alternative is to use a 3rd party library which is react visibility sensor.

React Visibility Sensor

This pacakge is a Sensor component for React that notifies you when it goes in or out of the window viewport.

Installation

You can install this pacakge with below command

npm install react-visibility-sensor

How to use react Visibility Sensor

To use it you need to import the component using below command
import VisibilitySensor from "react-visibility-sensor";

and just need to wrap your own component with VisibilitySensor.

<VisibilitySensor onChange={onChange}>
      <div>...content goes here...</div>
    </VisibilitySensor>

Let’s create an example where we are going to render a large list and only going style visible list items.

  {lists.map(list => {
            return containmentDOMRect ? (
              <VisibilitySensor key={list} containment= 
               {containmentDOMRect}>
                {({ isVisible }) => {
                  return (
                    <div
                      style={{
                        height: 100,
                        lineHeight: "100px",
                        color: "white",
                        backgroundColor: isVisible ? "#593" : "#F33",
                        margin: 5
                      }}
                    >
                      I am #{list}
                    </div>
                  );
                }}
              </VisibilitySensor>
            ) : null;
          })}

It provides a prop to its child i.e isVisible. Based on that prop we can use our own custom styling for child components.

How to show components with partial visibility

It also take care of that if you want to display components with partial visibility you can add a prop partialVisibility to VisibilitySensor. Which is false by default.

How to use custom container for the React visibility Sensor

If you want to use custom container then you can use the prop containment which gonna accept a dom element. By default it uses browser viewport.

Where you can use it

You can use it on various places but most common are given below:

  • You can use it show thanks for visiting messages at scroll end of a page.
  • To load new data using api only when a specific component is visible.
  • Lazy load the component.
  • Load more content or comments when scrolls.
  • A bunch of more areas.
Edit 76898

Ref

If you want to learn how to render a large list efficentely in reactjs. You can check that here.

Categories: Reactjs