An analytics module for React.
- React 0.14+
- IE10+
- Unobtrusive feature injection through a root application component.
- Supports page view tracking.
- Supports both imperative and declarative custom link tracking.
- Provides a custom event tracking API.
- Supports multiple simultaneous analytics vendor tracking.
$ npm install --save react-metrics
React Metrics depends on Promise to be available in browser. If your application support the browser which doesn't support Promise, please include the polyfill.
Refer to the docs for more information on configuration.
// Application.jsimport{metrics}from"react-metrics";constconfig={vendors: [{name: "Google Analytics",api: newGoogleAnalytics({trackingId: "UA-********-*"})}],pageViewEvent: "pageLoad",pageDefaults: ()=>{return{siteName: "My Web Site",
...
};}}Compose your top level application component with metrics in order to provide metrics to all components and automatically enable page view tracking.
// Application.jsclassApplicationextendsReact.Component{render(){return({this.props.children});}}exportdefaultmetrics(config)(Application);Alternatively, if your development environment supports ES7, use the @decorator syntax instead:
// Application.js
@metrics(config)classApplicationextendsReact.Component{render(){return({this.props.children});}}Your application will now automatically trigger page view tracking.
a. Use data- attributes to enable custom link tracking on your DOM elements.
// PaginationComponent.jsclassPaginationComponentextendsReact.Component{render(){const{commentId, totalPage, currentPage}=this.props;return(<ul><liclassName={currentPage>0 ? "active" : ""}><ahref="#"data-metrics-event-name="commentPageClick"data-metrics-comment-id={commentId}data-metrics-page-num={currentPage-1}>
Back
</a></li><li>...</li><liclassName={currentPage<totalPage-1 ? "active" : ""}><ahref="#"data-metrics-event-name="commentPageClick"data-metrics-comment-id={commentId}data-metrics-page-num={currentPage+1}>
Next
</a></li></ul>);}}b. Use MetricsElement for custom link tracking on a nested DOM element.
Please see MetricsElement for more use cases.
import{MetricsElement}from"react-metrics";// PaginationComponent.jsclassPaginationComponentextendsReact.Component{render(){const{commentId, totalPage, currentPage}=this.props;return(<ul><liclassName={currentPage>0 ? "active" : ""}><MetricsElementelement="a"href="#"data-metrics-event-name="commentPageClick"data-metrics-comment-id={commentId}data-metrics-page-num={currentPage-1}><spanclassName="button">Back</span></MetricsElement></li><li>...</li><liclassName={currentPage<totalPage-1 ? "active" : ""}><MetricsElementelement="a"href="#"data-metrics-event-name="commentPageClick"data-metrics-comment-id={commentId}data-metrics-page-num={currentPage+1}><spanclassName="button">Next</span></MetricsElement></li></ul>);}}react-metrics does not automatically supply any vendor analytics. You need to integrate with an analytics vendor to actually track something for reporting.
Refer to Vendor Examples for Omniture, Google Analytics and other implementations.
Also check out the awesome segmentio library which provides a lot of third party analytics vendors.
Use the @exposeMetrics decorator and willTrackPageView() methods on a route-handling component to override the default page view tracking behavior and pageDefaults data.
- Example: disable automatic page view tracking and trigger page view tracking manually.
// PageComponent.js// Must be a "route handling" component: <Route path="my-page" component={PageComponent}/>import{exposeMetrics,PropTypes}from"react-metrics";
@exposeMetricsclassPageComponentextendsReact.Component{staticcontextTypes={metrics: PropTypes.metrics}staticwillTrackPageView(){// first, suppress the automatic call.returnfalse;}componentDidMount(){const{value1, value2}=this.props;this.context.metrics.pageView({value1, value2});}render(){
...
}}- Example: add custom data to automatic page view tracking.
// PageComponent.js "route-handler// A route handling component: <Route path="my-page" component={PageComponent}/>import{exposeMetrics}from"react-metrics";
@exposeMetricsclassPageComponentextendsReact.Component{staticwillTrackPageView(routeState){// return a promise that resolves to custom data.returnyourPromise.then(data=>{// data gets merged with `pageDefaults` objectreturndata;});}render(){
...
}}Use this.context.metrics.track() to trigger custom event tracking as an alternative to declarative custom link tracking.
Define metrics as a contextType in your component and trigger custom track events using metrics.track().
import{PropTypes}from"react-metrics";classYourComponentextendsReact.Component{staticcontextTypes={metrics: PropTypes.metrics}onSomethingUpdated(value){this.context.metrics.track("customEventName",{value});}render(){
...
}}react-metrics provides a low level factory API; this is convenient for exposing an instance of the metrics API outside of a React component.
Use createMetrics to create a metrics instance and expose the metrics.api.
// creating middleware for Reduximport{createMetrics}from"react-metrics";constmetrics=createMetrics(config);exportdefaultfunctionmetricsMiddleware(){returnnext=>action=>{constreturnValue=next(action);switch(action.type){caseActionTypes.ROUTE_CHANGE:
const{location}=action;constpaths=location.pathname.substr(1).split("/");constrouteState=location;metrics.setRouteState(routeState);metrics.api.pageView({category: !paths[0] ? "landing" : paths[0]});}returnreturnValue;};}- API Review the
metricsAPI - Getting Started A more detailed Getting Started Guide
- Vendor Examples Omniture, Google Analytics, and other analytics vendor examples.
- Docs Guides, API, and examples.
- Clone this repo
- Run
npm install - Run
npm run examples - Point your browser to http://localhost:8080
Please take a moment to review the guidelines for contributing.
MIT