Add analytics on links in React.
Recently I joined a team with with a large React front-end. I was tasked with figuring out how to add analytics to a ton of buttons and links throughout the application. I wanted an easy way to add analytics without having to write
onClick event handlers which would fire events from a library like react-ga.
For the sake of this demo, I’ll be talking about how I added Google Analytics for user-driven event tracking, but you can bring whichever fancy analytics library satisfies you.
The easiest solution I thought of was to create a new
<A> React component which would substitute html
<a> links. It would do so by intercepting the
onClick() event, running the analytics library code, and then continuing to the the child’s
onClick() event if it existed. Clicked links open normally if the
href property is present, and all the regular properties (such...
Continue reading →