Add pageview event to google tag manager + gatsby

1.5k views Asked by At

I am tryting to add custom data layer snippet (dataLayer.push(❴’event’: “pageview”❵)) to Gatbsy GTM plugin. How do I do it? Anybod help?

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ originalLocation: document.location.protocol + '//' + document.location.hostname + document.location.pathname + document.location.search });
1

There are 1 answers

2
Ferran Buireu On

Use a useEffect hook in your component/page. A useEffect is an event that is triggered once the DOM tree is loaded (similar to componentDidMount, componentDidUpdate, and componentWillUnmount lifecycles combined).

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

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (typeof window !== 'undefined'){
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ originalLocation: document.location.protocol + '//' + document.location.hostname + document.location.pathname + document.location.search });
    }
  }, []);

  return (
    <div>
      <p>Your page</p>
    </div>
  );
}

Note the typeof window !== 'undefined' condition, a recommended statement when dealing with global objects (such as window or document) in server-side rendering.