React Riddles: The Mysterious Case of the Untracked Clicks
Tags: react, javascript, webdev, frontend
Published: 2023-07-21 11:00:00

_In this series, you confront real-world React mysteries. It's an opportunity to test your skills and flex your debugging muscles on realistic problems that you could encounter on the job and during job interviews._

Recently, I encountered a perplexing bug affecting our analytics data on my day job. We noticed something strange - in certain instances, our tracking events would fire up perfectly, but at other times, they wouldn't activate at all. It was a mysterious problem that needed solving, and it all started with the way we were tracking clicks on a button.

*If you’re rather a video person you can watch the complete review and refactoring session here.*

{% embed https://youtu.be/vUtxNmGeQhA %}

## The Mystery

Allow me to share an example of our button tracking code for better clarity ([you can find the complete code here on StackBlitz](https://stackblitz.com/github/jkettmann/react-riddles-tracking-hook?file=src%2Fuser.tsx,src%2Fuse-tracking.ts)):

```typescript
import { useRef } from "react";
import { useTracking } from "./use-tracking";
import { Button } from "./button";
import { ReactComponent as EditIcon } from "./edit.svg";

export function User() {
  const containerRef = useRef<HTMLDivElement>(null);
  useTracking(containerRef, "user-profile", { authStatus: "authenticated" });

  return (
    <div ref={containerRef}>
      <Button data-tracking-id="edit">Edit</Button>
      <Button data-tracking-id="edit-icon" icon={<EditIcon />} />
    </div>
  );
}

```

This tracking system relied on a `useTracking` hook. To keep things simple, I'll share a more straightforward version of it:

```typescript
import { MutableRefObject, useEffect } from "react";

export function useTracking(
  containerRef: MutableRefObject<HTMLElement | null>,
  containerId: string,
  trackingParams?: Record<string, string>
) {
  useEffect(() => {
    // container not yet mounted
    if (!containerRef.current) {
      return;
    }
    const container = containerRef.current;

    // the callback that sends the tracking event
    const listener = (event: Event) => {
      // get the tracking id from the data attribute (e.g. data-tracking-id="button-1")
      const target = event.target as HTMLElement;
      const trackingId = target.dataset.trackingId;

      // Send tracking event
      if (trackingId) {
        console.log(`Tracking ${containerId} ${trackingId}`);
        window.tracking.push([containerId, trackingId, trackingParams]);
      }
    };

    container.addEventListener("click", listener);
    return () => {
      container.removeEventListener("click", listener);
    };
  }, [containerRef, containerId, trackingParams]);
}

```

This system worked like a charm, that is, until we started incorporating more icon buttons:

```typescript
export function User() {
  const containerRef = useRef<HTMLDivElement>(null);
  useTracking(containerRef, "user-profile", { authStatus: "authenticated" });

  return (
    <div ref={containerRef}>
      <Button data-tracking-id="edit">Edit</Button>
      <Button data-tracking-id="edit-icon" icon={<EditIcon />} />
    </div>
  );
}

```

And then, our mysterious bug reared its ugly head: why on earth was the tracking event firing for the text button but not for the icon button?

![Tracking event not firing for icon button](no-optimization::https://media.graphassets.com/yF4sOtymSCHW8qjtRusI)

Let's dig into this curious issue in the next section.

## A Quick Note Before We Begin

As you venture into this blog post, I encourage you to treat it not just as a read, but as an interactive exercise. As we journey through a real-world bug in our code, try to come up with your own solutions before you continue to the next section. Trust me; it's more fun and informative this way!

This isn't just a casual recommendation. The problem at hand is similar to those you might encounter during a job interview for a developer role. Working through it on your own will give you a taste of real-world challenges and offer valuable practice for such scenarios. It's not just about the specific bug; it's also about flexing those problem-solving muscles and honing your analytical skills.

Moreover, this exercise even incorporates a touch of algorithmic thinking - a vital skill in the realm of programming. So put on your thinking caps and dive right in. Let's crack this bug together!

## Debugging the Issue

Debugging in the world of programming can be a complex task, but the most straightforward way to begin here is to set a breakpoint using Chrome dev tools. This allows us to observe the behavior of our code while it's running and catch any irregularities.

When we click on the “Edit” text button, we see that the `trackingId` is indeed defined, which enables the tracking event to fire as expected.

![](https://media.graphassets.com/ja3PtntxTcGD5oNWEgle)

However, a different story unfolds when we click on the icon button: the `trackingId` comes out as `undefined`.

![](https://media.graphassets.com/Ac0ecurxT66AdyqV7khf)

### So, why isn’t the `trackingId` defined when clicking on the icon button?

Here's a bit of a mystery for you. Can you figure out the answer before moving on?

![](no-optimization::https://media.graphassets.com/Pjx5D7qyTEijUjzsbDAn)

### Unmasking the culprit

It took me a bit to grasp this during my investigation, but the answer lies in the specifics of the click event. When we click on the SVG icon, we're actually interacting with the SVG element itself.

![](https://media.graphassets.com/kW75DyTgT1GF5d9Ligwi)

But here's the catch: our tracking ID isn't set on the SVG element - it's set on the button, which is the parent element.

![](https://media.graphassets.com/D9tKn6RTamJppc9VkFOQ)

So, how can we solve this? 

### I encourage you to give it a shot before moving forward.

This could well be one of these real-world algorithm questions you’ll ask in a job interview!

![](no-optimization::https://media.graphassets.com/KE5ea7TRQrqVTqY1mGKw)

## First, let's understand how the useTracking hook works

In our component, we pass a reference to the container element to the hook.

![](https://media.graphassets.com/gPrXxHy5SX6zeBWncKOt)

Within the hook, we attach a click listener to this container.

![](https://media.graphassets.com/WHDASHTnRva8opp9d1yz)

Now, it's crucial to note that this listener isn't triggered only when we click on the container element itself. **Due to the bubbling nature of events in JavaScript, this listener is activated for any clicks on its child elements.** So, if we click one of the buttons, the click event propagates to the container, triggering the listener. Inside this listener, we retrieve the data attribute `trackingId` from the event target and only fire the tracking event if `trackingId` is defined.

![](https://media.graphassets.com/fo6yiXthTkiScqhxPOZJ)

Here's where the issue arises: when we click the text button, the event target is the `button` element, which possesses a tracking ID. However, when we click on the icon inside the button, the event target becomes the `svg` element, which doesn't have a tracking ID.

![](https://media.graphassets.com/oyPUVFE6TAaLrH1ryEdt)

Now that we've outlined the issue, we can move on to the solution. But are you sure you don't want to give it a shot on your own first?

![](no-optimization::https://media.graphassets.com/12NFOAQ8Ti2SF8tDaEgb)

## The solution: Recursion to the rescue

The first thought you might have is to check both the event target and its parent element for a tracking ID. You're on the right track, but there's a twist: if you click on the icon button often enough, you might hit the `path` element within the `svg`. In this case, the parent’s parent would be the element with the tracking ID.

We want to create a tracking hook that works universally, even with complex elements like clickable cards that have many nested child elements. The solution? Use a recursive approach to explore each parent element of the original event target until we locate an element with a `data-tracking-id` attribute.

```typescript
function getTrackingId(element: HTMLElement | null) {
  // Stop condition: the previous element doesn't have a parent.
  // We're at the root of the tree.
  if (!element) {
    return null;
  }
  const trackingId = element.dataset.trackingId;
  // Stop condition: we return when the element has a tracking ID
  if (trackingId) {
    return trackingId;
  }
  // continue recursively traversing the tree
  return getTrackingId(element.parentElement);
}
```

Now, we can use this function to retrieve the tracking ID from any parent element.

```typescript
export function useTracking(
  ...

  useEffect(() => {
    const listener = (event: Event) => {
      const target = event.target as HTMLElement;

      // use the new recursive function to get the tracking ID from
      // any parent element
      const trackingId = getTrackingId(target);

      if (trackingId) {
        console.log(`Tracking ${containerId} ${trackingId}`);
        window.tracking.push([containerId, trackingId, trackingParams]);
      }
    };

    ...

```

And voila, it works!

![](no-optimization::https://media.graphassets.com/6Aj9j1xpSQKlnFQbruuE)

However, this recursive approach does come with a minor drawback. Suppose we click on a child of a tracking container that we don't want to track. In that case, we'll still traverse all the parent elements even though we're not interested in this click event. For some apps, this might cause performance issues. However, for most apps, this should be manageable, as there typically aren't thousands of parent elements to go through.

## A Sneak Peek at What's Next

Just when you think we've squashed that bug and our code is as clean as a whistle, a wild mystery appears! Yes, you heard it right. Hidden within the nooks and crannies of our code is another bug, patiently waiting to be discovered.

But worry not! We're not going to leave you hanging. This intrigue sets the stage for our next blog post, where we'll embark on yet another bug-hunting adventure. We'll take our detective hats out once again and get down to dissecting this elusive code miscreant.

So, stay tuned and gear up for another round of digital troubleshooting. We'll dig deeper, learn more, and emerge victorious once again in our journey through the fascinating world of code! Until then, happy coding!