Is it somehow possible to track custom events with gatsby and google analytics?
Finding Custom Events In Google Analytics 4 Reports Feel free to trigger the event yourself so that your GA4 reports have some event data to compile. The built-in reporting function can be found here: Click the Reports tab in GA4 left side menu. Click Engagement, then Events.
Hence you will see a more diverse list of collected values in your GA4 reports. If you want to send more parameters, you are free to include up to 25 custom parameters with a single event.
Add Google Analytics via official pluginAdd the plugin to your gatsby-config. js file: module. exports = { plugins: [ // All other plugins { resolve: `gatsby-plugin-google-gtag`, options: { // You can add multiple tracking ids and a pageview event will be fired for all of them.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With