How it works

An example

This will take you through the virtual DOM structure of an example react app, showing you where different properties were added. At the end you can see what an example event looks like.

1. MetricsProvider

We use the MetricsProvider like we would the redux Provider. Pass it your analytics api and any initial properties. In this example, we get the packageJson and pass the version property to MetricsProvider.

Now all events will inherit the version property
import packageJson from 'src/package.json

export default function App() {
  
  return (
    <MetricsProvider
      analytics={{
        track: (name, props) => {/*...*/},
        page: (name, props) => {/*...*/}
      }}
      properties={{
        version: packageJson.version,
      }}
    >
      {/*...The rest of your app*/}
    </MetricsProvider>
  )
}                  

2. AddProperties

Then, say we find a user, saved in localStorage, and we want to pass the user's "userId" to all events and pageviews. We will use the AddProperties component.

Now all events will inherit the version, and userId properties
export default class Auth extends Component {
  
  handleLogin = () => {
    // ... Login user
    this.setState({userId})
  }
  
  render() {
    const {userId} = this.state
    return (
      <AddProperties properties={{userId}}>
        <Route
          exact
          component={Home}
          path="/"
        />
      </AddProperties>
    )

}                  

3. PageView

In the Auth component above, we used a Route component from react-router v4 to display the Home page when the pathname is "/" (the root path). In the following example we will demonstrate how to use the PageView component.

You can wrap the whole page in PageView or just put it on the page next to your content, like so:

<PageView /*{...props}*/ />

Use the ready prop to wait to use the analytics.page method until all necessary properties have been added.

Now all events will inherit the version, and userId properties
export default function Home() {
  return (
    <PageView 
      ready={initialized}
      name="Homepage Viewed"
      properties={{
        // ...additionalProperties
      }}
    >
      {/*The rest of your home page...*/}    
    </PageView>
  )
}                  

4. connectMetrics

The connectMetrics higher order component will get all the metrics data (aka. metrics "bag"), which includes analytics and properties (all inherited properties at this depth in the virtual DOM).


export default function connectMetrics(Navbar({metrics}) {
  
  const {
    analytics,
    properties
  } = metrics
  
  const logout = () => {
    analytics.track('User Logged Out', {
      ...properties,
      /* Any additional properties */
    })
    
    // The rest of your logout logic ...
  }
  

})