React
+ GoogleAanaytics
でトラッキングをするにはライブラリがあるのでそれを使う。
スター数も1000
超えてるし、React + GA
でなら一番人気かと思う。
インストールする際のバージョンに注意
react-ga
には2.3.4
において、初回のイベント以外は送信できないという致命的なバグが存在してる。
(だいぶ困ってた)
少なくともうちで使っている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();
ここら辺何かクールなやり方があれば知りたい・・。