いっきのblog

技術とか色々

React + GoogleAnayticsでページトラッキングする

React+ GoogleAanayticsでトラッキングをするにはライブラリがあるのでそれを使う。

github.com

スター数も1000超えてるし、React + GAでなら一番人気かと思う。

インストールする際のバージョンに注意

react-gaには2.3.4において、初回のイベント以外は送信できないという致命的なバグが存在してる。
(だいぶ困ってた)

github.com

少なくともうちで使っている2.3.5ではすでに修正されているので、それ以降のバージョンをいれるようにしたほうがいい。

遷移するたびにトラッキングする

一つ一つのページに設置するのはめんどくさいので、ページの状態がかわったら送信するようにする。

まず、トラッキングするための親コンポーネントを作成する。

import React, {Component} from "react";
import {Route, withRouter} from "react-router-dom";
import * as titleUtil from "./util/Title";
import * as GaUtil from "./util/GA";

GaUtil.initialize();

class TrackPageView extends Component {

  componentWillMount() {
    this.track();
  }

  componentDidUpdate() {
    this.track();
  }

  track() {
    const currentPath = this.props.location.pathname;
    
    // タイトルが動的なパスはここでは送信しない
    if (GaUtil.isCustomTrackingPath(currentPath)) {
      return;
    }
    
    // パスに紐づくタイトルを設定する(固定)
    document.title = titleUtil.getTitleByPathName(currentPath);
    GaUtil.sendPageView();
  }

  render() {
    // 子コンポーネントを呼び出す
    return <Route children={this.props.children}/>
  }
}

// withRouterを使うことで、色々な遷移に対応できる
export default withRouter(TrackPageView);

次にRouteにあるコンポーネントたちをTrackPageViewの子要素する。

<BrowserRouter>
  // 囲う
  <TrackPageView>
    <Switch>
      <Route exact path="/" component={Lp}/>
      <Route exact path={ROUTE.Client.Login} component={ClientLogin}/>
      <Auth>
        <Switch>
          <Route exact path={ROUTE.Client.Item.Index} component={Items}/>
          <Route component={NotFound}/>
        </Switch>
      </Auth>
    </Switch>
  </TrackPageView>
</BrowserRouter>

こうすることで、子要素のコンポーネントcomponentWillMountが呼ばれる際に毎回トラッキングすることが可能になる。

タイトルが動的に変わるパスの設定

現状は子コンポーネントでデータを取得した際に、以下のように呼んでいる。

document.title = v.name + 'の詳細';
GaUtil.sendPageView();

ここら辺何かクールなやり方があれば知りたい・・。