gabefromutah / gatsby-plugin-facebook-pixel

Gatsby plugin to add facebook pixel onto a site
15 stars 21 forks source link

Example of binding a fbq event to a click #7

Open samuelgoddard opened 4 years ago

samuelgoddard commented 4 years ago

Hey, thanks for the plugin, it's working perfectly. However, I want to bind a fbq event to a button click but unsure how to do this, it works fine for me in production but locally my components obviously have no idea what fbq is. Could you share an example of how to get around this?

simply doing this:

contactClick = () => {
    fbq('track', 'Contact')
  }

and binding it to a click event works fine when the site is built, just breaks locally as it doesn't know what fbq is

Thanks in advance, San

jonsherrard commented 4 years ago
export default function fbTrack(a,b) {
  if (process.env.NODE_ENV === `production` && typeof fbq === `function`) {
    fbq(a, b);
  }
}
import fbTrack from './fb-track'

contactClick = () => fbTrack('track', 'Contact')
janukasama commented 4 years ago

@jonsherrard Thanks for the code but how do I overcome ''fbq' is not defined'?

rmagon commented 4 years ago

@janukasama Hey, were you able get this working ?

maxcct commented 4 years ago

@jonsherrard Thanks for the code but how do I overcome ''fbq' is not defined'?

The typeof fbq === "function" check in the example given by @jonsherrard should take care of this. However, if your problem is that eslint or something like that is refusing to compile with it there, then putting something like // eslint-disable-line no-undef alongside it is what you want.

gabefromutah commented 3 years ago

@samuelgoddard, am I able to close this issue out?

joeljackson commented 3 years ago

This could be generalized to "How to create any event in facebook"

For example after a successful e.comm conversion, I want to run

fbq('track', 'Purchase', { currency: "USD", value: cart.total() });

then clear the items in the cart when the page loads. But, gotta wait until fbq is available

jonsherrard commented 3 years ago

All you'd have to do is add the third parameter by an= update the code in my example to:

export default function fbTrack(a,b, c) {
  if (process.env.NODE_ENV === `production` && typeof fbq === `function`) {
    fbq(a, b, c);
  }
}