Adding Segment telemtry to React component that is only one DOM node

102 views Asked by At

I'm looking to add segment analytics to my JupyterLab extension. No worries if you've never heard of a JupyterLab extension - the best way to think about it: I get control over a single node in the DOM where I can place some HTML, so I'm doing the following:

function Welcome(props) {return <h1>Hello</h1>;}
ReactDOM.render(<Welcome/>, dom_element_i_control)

This all works fine - I'm now looking to add some analytics code to this. For example, I'd like to be able to:

  1. See when my code is rendered
  2. See when someone interacts with my rendered element (e.g. if there was a button in the Welcome function, when the user clicked on it).

However, segment is a JS library that is delivered as a script that you load into a webpage at the top in a string tag like:

<script>
  !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&...}}();
</script>

Where would I even put this code? I don't have control over the larger page + HTML, so I'm not sure where I can slap this so I can start using analytics.

Thanks for any information!

1

There are 1 answers

0
Nate Rush On

My workaround:

  1. Instead of using the above linked segment script, I used the analytics-node package from segment.
  2. I create an Analytics object right before ReactDOM.render - and then can use it wherever I want :)

Note that this will not work for anyone who uses an add blocker, obviously!