How to call zaraz's web api functions in React JS app?

Hello, all. I want to ask if anyone try implementing the zaraz.track function inside react js?

Recently I tried to directly call zaraz.track function to track a CTA button click inside my GatsbyJS project like this

<div>
            {cta && (
              <Button
                to={cta.href}
                onClick={zaraz.track("cta_link_click", {
                  link_text: `${cta.text}`,
                  link_url: `${cta.href}`,
                })}
              >
                {cta.text}
              </Button>
            )}
          </div>

And then I got this build error output info WebpackError: TypeError: zaraz.track is not a function. So I want to know how to implement the Zaraz web API functions correctly inside React JS, any suggestions?

Hello @sadduck

Are you using auto-inject? I don’t have a gatsby project nearby to test on but I feel that if you get the error at build time, it may be linked to the auto-inject (which happens at run time, so no zaraz object exists at build time)

Could you try using window.zaraz.track instead? If that does not work, you could maybe have a wrapper in your or that test whether zaraz exists and if not set it to a dumb function like:

zaraz = window.zaraz || { function track() { console.log(Zaraz track called with ${arguments})} };

Thank you!

For those who meet the same problem, here is my solution inspired by @lucaskostka54


<Button
onClick={() => {
if (window.zaraz) {
window.zaraz.track(“cta_link_click”, {
link_text: ${cta.text},
link_url: ${cta.href},
})
}
console.log(“button clicked”, ${cta.href}, ${cta.text})
}}
type=“button”
to={cta.href}
>
{cta.text}

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.