Check if an Element is in the Viewport in React.js

This article will show you how to check if an element is in the Viewport in React.js. The article will cover some ways, like using the useIsInViewport() hook or using IntersectionObserver.

How to check if an Element contains a class in React

Install use-is-in-viewport package

The use-is-in-viewport is a package hook created by an individual developer to let us quickly check if an element is in the Viewport in React.js. This library uses the react hook. You can use the IntersectionObserver declaratively in your React app to determine whether an element is in a particular viewport. You can install this library with the npm command like below:

npm install use-is-in-viewport

After the package has been successfully installed, you can follow the below code to learn how to use this predefined useIsInViewport hook.

Code:

import React from "react";
import useIsInViewport from "use-is-in-viewport";

function App() {
    const [isInViewport1, targetRef] = useIsInViewport();
    const [isInViewport2, targetRef2] = useIsInViewport();

    return (
        <>
            <div ref={targetRef}>
                Header {isInViewport1 ? " is in viewport" : "is not in viewport"}
            </div>
            <div style={{ height: "100rem" }} />
            <div ref={targetRef2}>
                Footer{isInViewport2 ? " is in viewport" : "is not in viewport"}
            </div>
        </>
    );
}

export default App;

Output:

Header is in viewport

Running the above code, you can see that when we are in the viewport header, there will be a message “Header is in viewport”, but when you scroll away, the program will detect it is out of viewport and change the message. All you need to do is import the useIsInViewport hook from the package and use it. The value passed to this hook is a ref that we need to check and a variable to store the test value. Or you can also refer to another method in the next part of the article.

Using IntersectionObserver method

The Intersection Observer API provides a way to asynchronously observe changes in the interface with ancestor elements or high-level document viewports.

The viewport is a frame, possibly a polygonal area on the screen that you are seeing. In a web browser, it refers to the portion of the document the user sees, which is visible in the application window or on the screen if displayed on full screen. The parts outside the viewport are what you only see once you scroll to it. This method is a manual way of doing it, and we will create our test hook.

Code:

import { useEffect, useRef, useState, useMemo } from "react";

export default function App() {
    const ref = useRef(null);
    const ref1 = useRef(null);
    const isInViewportHeader = useIsInViewport(ref);
    console.log("isInViewportHeader: ", isInViewportHeader);
    const isInViewportFooter = useIsInViewport(ref1);
    console.log("isInViewportFooter: ", isInViewportFooter);

    return (
        <div>
            <div ref={ref}>Header {isInViewportHeader && "is in viewport "}</div>
            <div style={{ height: "100rem" }} />
            <div ref={ref1}>Footer{isInViewportFooter && "is in viewport "}</div>
        </div>
    );
}

function useIsInViewport(ref) {
    const [isIntersecting, setIsIntersecting] = useState(false);
    const observer = useMemo(
        () =>
            new IntersectionObserver(([value]) =>
                setIsIntersecting(value.isIntersecting)
            ),
        []
    );

    useEffect(() => {
        observer.observe(ref.current);
        return () => {
            observer.disconnect();
        };
    }, [ref, observer]);
    return isIntersecting;
}

Output:

isInViewportHeader: true
isInViewportFooter: false

In this way, we will build a hook useIsInViewport to check if the element is in the viewport, pass the IntersectionObserver method a value to check, and it will return us true or false to save into the test state. For example, if we are a viewport header, the check value of the header element will be true, and the footer will be false.

Summary

The article showed you how to check if an Element is in the Viewport in React.js. However, I recommend installing the use-is-in-viewport package because the hook is already built for us.

Leave a Reply

Your email address will not be published. Required fields are marked *