LoginSignup
57
36

More than 3 years have passed since last update.

GoogleアナリティクスをReactで使う方法

Last updated at Posted at 2018-11-08

GoogleアナリティクスをReactで使う方法

サンプルソースコード

以下のリポジトリにてサンプルを確認することができます。(react + router + reduxの構成)
https://github.com/solt9029/react-ga-tutorial

普通のHTMLページだったら?

Googleアナリティクスを普通のHTMLページで使う場合、ヘッダーに以下のようなタグを追加します。

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-128421111-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-128421111-1');
</script>

しかし、Reactを使ったSPAの場合、これだけだとうまくいきません。
(※ページ遷移はReact Routerで行っているものとします)

そのため、react-gaというモジュールを使って設定していきます。
かなり単純ですが、ちゃんと一通り書いていた記事が見つからなかったので、この記事にまとめました。

react-gaでGoogleアナリティクスをReactで使うよ!

まずreact-gaが必要です。
yarnを使っている場合には以下の通りです。

yarn add react-ga

npmを使っている場合には以下の通りです。

npm install --save react-ga

普通にReactの開発をしていれば、src/index.jsの中でhistoryを作っているかと思います。(そうでない場合は、読み替えていってください。)

import createBrowserHistory from 'history/createBrowserHistory';
const history = createBrowserHistory();
// (以下略)

このindex.jsに以下のようなコードを加えます。

import ReactGA from 'react-ga';
import createBrowserHistory from 'history/createBrowserHistory';

ReactGA.initialize('UA-128421111-1');
const history = createBrowserHistory();
history.listen(({ pathname }) => {
  ReactGA.set({ page: pathname });
  ReactGA.pageview(pathname);
});
// (以下略)

history.listenで、React Routerによってページ遷移するごとに、Googleアナリティクスに情報が送信されるようになりました。

しかし、初めてindex.htmlが返されるときに、Googleアナリティクスに情報が送信されません。(ページ遷移ではなく、直接そのサイトにアクセスしたとき)

そこで、App.jsにcomponentDidMountでGoogleアナリティクスに情報を送信するプログラムを書きましょう。

import ReactGA from 'react-ga';
// (略)

export default class App extends Component {
  componentDidMount() {
    const { pathname } = this.props.location;
    ReactGA.set({ page: pathname });
    ReactGA.pageview(pathname);
  }
// (略)
}

以上です!

57
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
57
36