pixelplicity/gatsby-plugin-plausible

Examples for "Triggering custom events"

Opened this issue · 1 comments

ekeih commented

Hi,

first of all thanks for this plugin!

Being rather new to JavaScript and React I have a hard time to wrap my head around the documentation for custom events.

I tried to get this to work for a few hours now and I think I understand why all my attempts fail (I think I always tried to evaluate it during the server side rendering of gatsby/react) but I still can't really figure out the right way to solve it. As far as I understand this code has to be evaluated on the client side when the page actually loads or the event is executed.

For example, I would like to include

window.plausible('404', {
  callback: () => console.info('custom 404 event logged'),
});

in my 404 error page and then use https://docs.plausible.io/404-error-pages-tracking/ to track those errors. What would be the right way to achieve this in gatsby? Do I need to do this in componentDidMount somehow?

I think the documentation would benefit from an example how to run such custom event at page load and on button press.
Any chance you could help me out here with a short explanation? I am happy to provide a pull request to extend the documentation afterwards :)

Thanks in advance
Max

ekeih commented

Okay, I think I got it working. In the end it turned out to be much simpler than I thought. For me the following works as a minimal 404 component which reports a custom 404 event to plausible.

// 404.js component
import React from "react"

export class NotFoundPage extends React.Component {
  render() {
    return (
      <p>You just hit a route that doesn&#39;t exist... the sadness.</p>
    )
  }

  componentDidMount() {
    if (!window.plausible) {
      console.log("Would have tracked: 404")
    } else {
      window.plausible("404")
    }
  }
}

export default NotFoundPage