/react-redux-google-analytics

react google analytics helpers and redux middleware

Primary LanguageJavaScript

react-redux-google-analytics

Installation

npm install react-redux-google-analytics --save

Contributions are welcome !

1) Initialize google analytics at the root of your application

initGa(googleAnalyticsId, propertyId, [gaOptions = 'auto'], [onlyInProduction = false])
// root component component did mount
componentDidMount() {
  initGa('UA-XXXXX', 'XX')
}

This function initializes google analytics and creates a windowga property.

2) Setup the middleware gaEventsMiddleware

gaEventsMiddleware

Redux middleware for google analytics.

If an action has a gaEvent property, then a google analytics event is triggered with the window.ga property.

Usage example:

import { createStore, applyMiddleware } from 'redux'
import todos from './reducers'
import { gaEventsMiddleware } from 'react-redux-google-analytics'

let store = createStore(
  todos,
  applyMiddleware(gaEventsMiddleware)
)

3) Attach an event to an action

withGaEvent(category, action, [label = ''], 
[value = 0], [fieldsObject = {}]) => (wrappedPayload)

Usage example :

import { withGaEvent } from 'react-redux-google-analytics'

export const addItem = (itemId) => withGaEvent('menu', 'add-item', itemId)(
  {
    type: TYPES.AN_ACTION_TYPE,
  }
)

Equivalent to :

export const addItem = (itemId) => ({
  type: TYPES.AN_ACTION_TYPE,
  gaEvent: {
    category: 'menu',
    action: 'add-item',
    label: itemId
  }
})

4) Trigger page view hit

gaPageView([page], [fieldsObject])

Usage with react router

import { gaPageView } from 'react-redux-google-analytics';
import { createBrowserHistory } from 'history';
  [...]

const history = createBrowserHistory();
history.listen((location) => gaPageView(location.pathname + location.search));

ReactDOM.render((
    <Router history={history}>
        [...]

5) Trigger events outside of redux actions if you like

gaEvent(category, action, label = '', 
value = 0, fieldsObject = {})