Gatsbyjs + Google analytics - tracking custom events?

I've used ReactGA in conjunction with Gatsby and had good success.

For basic event tracking - like logging a clicked link - it's very easy to use. You create a logging function in your component that accesses ReactGA.event and then invoke it in your render function using onClick.

Example component logging a PDF download:

import React from 'react'
import Link from 'gatsby-link'
import ReactGA from 'react-ga'

import logo from './logo.png'
import financials from './Annual_Report_Financials_2017_FINAL.pdf'

class LoggingDownload extends React.Component {
  logger() {
    // Detect each click of the financial PDF
    ReactGA.event({
      category: 'Financial Download',
      action: 'User clicked link to view financials'
    })
  }

  render() {
    return (
      <div>
        <nav className="nav-container">
          <Link to="/locations">
            <img className="logo" src={logo} alt="Logo" />
          </Link>
          <ul className="nav-item-container">
            <li className="nav-item">
              <a href="/shortsignup/" target="_blank">Join Us</a>
            </li>
            <li className="nav-item">
              <a href={financials} onClick={this.logger} target="_blank" id="financials-pdf">Financials</a>
            </li>
          </ul>
        </nav>
      </div>
    )
  }
}
export default LoggingDownload

There are tons more use cases - check out ReactGA docs.

Also: don't forget to include ggatsby-plugin-google-analytics in your gatsby-config.js file as a dependency to getting the above to work correctly:

{
  resolve: `gatsby-plugin-google-analytics`,
  options: {
    trackingId: "UA-#########-##",
    // Puts tracking script in the head instead of the body
    head: false,
    // Setting this parameter is optional
    respectDNT: true,
  }
}

For anyone who is still wondering, gatsby-plugin-google-analytics is not the approach I would take for google analytics. What you are looking for is gatsby-plugin-google-gtag. This plugin automatically sends pageviews, as well as makes the gtag event available on the window.

window.gtag("event", "click", { ...data })

Google also gives us migration docs for anyone who is still using gatsby-plugin-google-analytics you can find here (link also in the gatsby docs).