Skip to content

Instantly share code, notes, and snippets.

@reduxdj
Created April 26, 2019 17:06
Show Gist options
  • Select an option

  • Save reduxdj/c59e283847b0d82d1d7c6ddad6431045 to your computer and use it in GitHub Desktop.

Select an option

Save reduxdj/c59e283847b0d82d1d7c6ddad6431045 to your computer and use it in GitHub Desktop.
Tracking Wrapper
/*
TrackingWrapper trackingEvent={{type: EVENTS.ACCOUNT_SIDEBAR_CLICKED}} >
<StyledLinkButton
pathname={pathname}
to="/account"
>
<StyledLinkButton path="wishlists" pathname={pathname} to="/account/wishlists">
<h6>Wishlists</h6>
<svg width="30" x="0px" y="0px" viewBox="0 0 471 448" >
<path fill="#149d43" d="M235.5,0l-72.8,147.5L0,171.1l117.8,114.8L90,448l145.5-76.5L381,448l-27.8-162.1L471,171.1l-162.7-23.7L235.5,0L235.5,0z" />
</svg>
</StyledLinkButton>
</TrackingWrapper>
*/
import React from 'react'
import Mixpanel from 'helpers/mixpanel'
import PropTypes from 'prop-types'
import GTM from 'helpers/gtm'
import {EVENTS} from 'constants/mixpanel'
import {camelCase} from 'lodash'
const track = (trackingEvent) => {
const {type, ...props} = trackingEvent
Mixpanel.track(type, ...props)
console.log('Mixpanel Tracking:', type, props) //eslint-disable-line
}
const handleGTMTracking = (trackingEvent) => {
switch (trackingEvent.type) {
case EVENTS.ADD_ITEM_TO_WISHLIST:
return GTM.trackAddToWishlist(trackingEvent)
default:
return GTM.tag({event: camelCase(trackingEvent.type)})
}
}
export const TrackingWrapper = ({children, trackingEvent, gtm}) => {
const newChildren = React.Children.map(children, (child) => {
const onClick = () => {
track({...trackingEvent, ...child.props, children: undefined})
if (gtm)
handleGTMTracking(trackingEvent)
if (typeof child.props.onClick === 'function')
child.props.onClick()
}
return React.cloneElement(child, {...child.props, onClick})
})
return (newChildren || React.Fragment)
}
TrackingWrapper.propTypes = {
trackingEvent: PropTypes.shape({
type: PropTypes.string.isRequired
}).isRequired
}
export default TrackingWrapper
@reduxdj
Copy link
Author

reduxdj commented Apr 26, 2019

Creates a cloned element and handles the click.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment