Jason Sonderman
Jason Sonderman

Reputation: 21

Gatsby google-tagmanager plugin: how to access dataLayer.push

I have installed and configured the gatsby-plugin-google-tagmanager in my site, and I can record pageviews with no issue.

But I also need to track button clicks by doing a dataLayer.push in an onClick event. I am not seeing a way to give the onClick event of an element access to the dataLayer object.

It either gives me an error that dataLayer is undefined, or that gtag is undefined.

Any syntax on this would be appreciated.

Gatsby-config

{
  resolve: 'gatsby-plugin-google-tagmanager',
  options: {
    id: 'GTM-XXXXXXX',
  },
}

Function called on button onClick

handleButtonClick=()=>{ 
  dataLayer.push({event: 'Request Button Click'});
}

Upvotes: 2

Views: 1864

Answers (1)

David Shaw
David Shaw

Reputation: 21

This worked for me.

handleButtonClick=()=>{ 
  window.dataLayer.push({event: 'Request Button Click'});
}

Also, by default in development, the GTM script will not be run. That means window.dataLayer will be undefined.

Upvotes: 2

Related Questions