Skip to content

Instantly share code, notes, and snippets.

@gregblass
Last active September 21, 2019 17:30
Show Gist options
  • Save gregblass/203121fa071a04cf068e253ba0de2701 to your computer and use it in GitHub Desktop.
Save gregblass/203121fa071a04cf068e253ba0de2701 to your computer and use it in GitHub Desktop.
Expo/React Navigation - Google Analytics Integration
import React, { Component } from 'react'
import { RootNavigator } from './navigators'
import { GoogleAnalyticsTracker } from './utils/analytics'
import { GA_TRACKING_ID } from './constants'
class App extends Component {
// gets the current screen from navigation state
getCurrentRouteName = (navigationState) => {
if (!navigationState) {
return null
}
const route = navigationState.routes[navigationState.index]
// dive into nested navigators
if (route.routes) {
return this.getCurrentRouteName(route)
}
return route.routeName
}
render() {
const tracker = new GoogleAnalyticsTracker(GA_TRACKING_ID)
return (
<RootNavigator
onNavigationStateChange={(prevState, currentState) => {
const currentScreen = this.getCurrentRouteName(currentState)
const prevScreen = this.getCurrentRouteName(prevState)
if (prevScreen !== currentScreen) {
tracker.trackScreenView(currentScreen)
}
}}
/>
)
}
}
export default App
import { Constants } from 'expo'
import { Platform } from 'react-native'
export class GoogleAnalyticsTracker {
constructor(trackingId) {
this.trackingId = trackingId
}
toQueryString = (obj) => {
var str = []
for(var p in obj) {
if (obj.hasOwnProperty(p) && obj[p]) {
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
}
}
return str.join('&')
}
deviceModel() {
if (Platform.OS === 'ios') {
return Constants.platform.ios.model
} else {
return null. // Not sure if this is possible on Android? Suggestions welcome
}
}
trackScreenView = (screenName) => {
let hit = {
v: 1,
tid: this.trackingId, // Tracking ID
cid: Constants.deviceId, // Anonymous Client ID.
sid: Constants.sessionId, // Anonymous Session ID.
t: 'screenview', // Screenview hit type.
an: 'Your App Name', // App name.
av: '1.0.0', // App version.
cd: screenName, // Screen name / content description
dn: Constants.deviceName, // Device name.
dm: this.deviceModel(), // Device model.
on: Platform.OS, // Operating system.
ov: Platform.Version, // Operating system version.
ds: !Constants.isDevice, // If app is running on a device.
ao: Constants.appOwnership, // Returns expo, standalone, or guest.
ev: Constants.expoVersion // Expo version.
}
let options = {
method: 'get'
}
url = `https://www.google-analytics.com/collect?` +
`${this.toQueryString(hit)}` +
`&z=${Math.round(Math.random() * 1e8)}`
return fetch(url, options)
}
}