5

I received problems when trying to send data to GTM (google tag manager) in a React application. We already managed to put different scripts on the related page(s).

For example below is one of script we put in cart page:

class Cart extends Component {

  render() {
    const { cartItems } = this.props;
    return (
      <script
        dangerouslySetInnerHTML={{ __html: `
          window.dataLayer = window.dataLayer || [];
          window.dataLayer.push({
            event: 'viewCart',
            cartItems: ${cartItems}
          });
          window.history = window.history || [];
          window.history.pushState({
            page: 'Current Cart Page',
            events: 'viewCart',
            cartItems: ${cartItems},
          }, 'Current Cart Page');
        ` }}
      />
    );
  }
}

The above script will not executed when we access to cart page from another page (E.G.: home page), but when we refresh the page, it gets triggered.

It turns out that the data layer only pushed on pageLoad and DOMReady event. but not in historyChange

Has anyone encountered this before and know how to solve it?

Rohan Büchner
  • 5,333
  • 4
  • 62
  • 106
Kris MP
  • 2,305
  • 6
  • 26
  • 38

0 Answers0