Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setup displayName of important component #237

Closed
MrOrz opened this issue Mar 11, 2020 · 2 comments · Fixed by #254
Closed

Setup displayName of important component #237

MrOrz opened this issue Mar 11, 2020 · 2 comments · Fixed by #254

Comments

@MrOrz
Copy link
Member

MrOrz commented Mar 11, 2020

Discussion: https://g0v.hackmd.io/@johnson/ByAb_n24U#Tracking

According to gaearon, we can set displayName to components. It should be readable by Google Tag Manager with clicked elements' __reactInternalInstance$XXXXX - https://stackoverflow.com/a/48335220

We can set displayName property for components that we want to track usage (click). It helps React devtools debugging in production as well.

@MrOrz
Copy link
Member Author

MrOrz commented May 18, 2020

A Google Tag Manager custom variable setup like below will be able to track the React component name (if it's static displayName is set) of the clicked element (or clicked element's ancestor):

function() {
  var currentNode = {{Click Element}};
  var reactInstanceKey = Object.keys(currentNode).find(function(key){
    return  key.startsWith('__reactInternalInstance$');
  });
  
  if(!reactInstanceKey) return;

  var currentInst = currentNode[reactInstanceKey];
  
  while(currentInst) {
    if(currentInst.elementType &&
       currentInst.elementType.displayName &&
       // Ignore names like "WithStyles(ForwardRef(ButtonGroup))"
       currentInst.elementType.displayName.indexOf('(') === -1) {
      return currentInst.elementType.displayName;
    }
    currentInst = currentInst.return;
  }
}

However, most components in Cofacts code base do not have displayName -- some buttons we want to track isn't even an isolated component. I am switching to data-ga method property instead of displayName.

@MrOrz
Copy link
Member Author

MrOrz commented May 18, 2020

We use both data-ga and displayName in the end. data-ga provides greater flexibility because we can set different names for different occurrences, while displayName makes sure all clicks under a component will be recorded no matter where it is rendered.

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

Successfully merging a pull request may close this issue.

1 participant