A Playful Solution for Tracking Element Visibility in React.js! ๐ŸŒŸ

ยท

4 min read

Hello, amazing developers and fellow code enthusiasts! ๐ŸŒŸ Are you tired of chasing invisible elements and struggling with tracking their visibility in your React.js projects? Fear not! In this blog, I'll share a nifty, fun-filled method to keep an eye on the elusive elements without breaking a sweat. Let's dive in and unveil the magic! ๐Ÿš€

So I was working on a project that requires sending events whenever a Call-to-Action (CTA) button becomes visible on the screen an my website has numerous CTAs spread across different pages, and managing the visibility tracking for each button seems daunting. That's precisely where I found myself not too long ago. There could be more examples where you can use this. For example, showing the ads if the particular section is visible and scenarios like that.

In situations like these, finding an efficient and scalable solution becomes crucial. I needed a system that would streamline the process and allow me to manage all the CTAs from a single place. Enter the dynamic button component and the power of the Intersection Observer API. With just a few lines of code, I was able to tackle the visibility tracking challenge and simplify the management of CTAs on my website.

In this blog post, I will guide you through the steps I took to create a dynamic button component that effortlessly tracks the visibility of CTAs. You'll be amazed to discover how, with only 15-20 lines of code, you can efficiently handle visibility tracking for all your CTAs and save yourself from tedious, repetitive tasks. Let's dive in and explore this game-changing solution!

So I have started with a very basic thing which is creating a dynamic component that is responsible for all the CTAs

import React from 'react'

const DynamicButton = ({ onClickFunc, buttonText, classList }) => {
  return <button 
        className={classList.join(" ")}
        onClick={onClickFunc}
        > {buttonText} </button>;
};

export default DynamicButton;

Now we are good to go for adding magic to detect this element's visibility. Now we will use IntersectionObserver API for observing the element.

The Intersection Observer API is like a watchful guardian for web developers. It helps you keep an eye on elements as you scroll through a webpage. Imagine a helpful assistant notifying you whenever an element enters or exits your view. With the Intersection Observer API, you can effortlessly track when elements become visible or hidden, making it perfect for triggering actions or animations as you scroll down a page. It's a nifty tool that simplifies the process of monitoring element visibility and makes your web development life a whole lot easier!

import React, { useEffect } from 'react';

const DynamicButton = ({ onClickFunc, buttonText, classList }) => {

  useEffect(() => {
      const options = {
          root: null,
          rootMargin: '0px',
          threshold: 0.5,
      };
      const observer = new IntersectionObserver((entries) => {
          entries.forEach((entry) => {
              if (entry.isIntersecting) {
                  //This code will run when the attached element is visible
                 doWhatYouWantFunction();
              }
           });
       }, options);
       //But here we want an element for attaching this observer 
       observer.observe(#NEEDED_ELEMENT);
   }, []);

  return <button 
        className={classList.join(" ")}
        onClick={onClickFunc}
        > {buttonText} </button>;
};

export default DynamicButton;

Here we can pass the element by reading it from the DOM by the document.getElementByID("#NEEDED_ELEMENT") but we won't do it in this way because we have the power of react hooks๐ŸŽ‰ we will use that. We have useRef by the help of this hook we can create the reference of this element and we will do our magic with it.

import React, { useEffect, useRef } from 'react';

const DynamicButton = ({ onClickFunc, buttonText, classList }) => {
  const buttonRef = useRef();

  useEffect(() => {
      const options = {
          root: null,
          rootMargin: '0px',
          threshold: 0.5,
      };
      const observer = new IntersectionObserver((entries) => {
          entries.forEach((entry) => {
              if (entry.isIntersecting) {
                  //This code will run when the attached element is visible
                 console.log("Hola, I am visible");
                 doWhatYouWantFunction();
                 observer.unobserve(buttonRef.current); 
              }
           });
       }, options);
       if (buttonRef.current) {
          observer.observe(buttonRef.current);
       }
       return () => {
          if (buttonRef.current) {
            observer.unobserve(buttonRef.current);
          }    
      };
   }, []);

  return <button 
        ref={buttonRef}
        className={classList.join(" ")}
        onClick={onClickFunc}
        > {buttonText} </button>;
};

export default DynamicButton;

Now whenever the element appears our desired code will execute......yipieeeeโœŒ

Thank you for joining me on this coding adventure! ๐ŸŒŸ I hope you had a blast exploring the fascinating world of tracking element visibility with the Intersection Observer API. Now you possess the superpower to uncover the hidden and make your website shine bright. So go ahead, create wonders with your code, and always remember to keep it simple, fun, and full of delightful surprises! Happy coding and may your programming journey be filled with endless smiles and high-fives! ๐ŸŽ‰๐Ÿ˜„๐Ÿš€

ย