LoginSignup
7
6

More than 3 years have passed since last update.

react-ga の pageview をページ遷移毎に発火する with react-router v4

Last updated at Posted at 2018-08-28

まえがき

react-ga の issues に載ってた history.listen を使う方法 も試したけど、多めに発火したり欲しいタイミングで発火しなかったりしちゃってやめた。

気持ち

  • ページ遷移毎に pageview を発火したい
  • いちばんはじめにサイトを開いた瞬間にも発火したい
  • Routes の設定は別ファイルに書きたい
  • Routes.js には GA のことは書かずに関係を疎にしておきたい

方法

App.js
import React, { Component } from "react";
import { BrowserRouter } from "react-router-dom";
import ReactGA from "react-ga";
import routesGetter from "./Routes";
import { getGaId } from "./utils";

const Analitics = props => {
  ReactGA.pageview(
    props.location.pathname + props.location.search + props.location.hash
  );
  return null;
};

const Routes = routesGetter({ children: Analitics });

class App extends Component {
  constructor() {
    super();

    ReactGA.initialize(getGaId(), { debug: process.env.ENV === "dev" });
  }

  render() {
    return (
      <BrowserRouter>
        <Routes />
      </BrowserRouter>
    );
  }
}

export default App;
Routes.js
import React, { Fragment } from "react";
import { withRouter, Switch, Route } from "react-router-dom";
import PageA from "./PageA";
import PageB from "./PageB";

const routesGetter = ({ children: Children }) => {
  return withRouter(routesProps => {
    return (
      <Fragment>
        <Children {...routesProps} />
        <Switch>
          <Route
            exact
            path="/pages/a"
            render={props => <PageA {...routesProps} {...props} />}
          />
          <Route
            exact
            path="/pages/b"
            render={props => <PageB {...routesProps} {...props} />}
          />
        </Switch>
      </Fragment>
    );
  });
};

export default routesGetter;

意図したとおりに動いた。ページを戻っても進んでも発火する。

あとがき

もっといい感じに実装できればコメントください!
https://gist.github.com/moriyuu/0a4a46dbb0f002434ab1a43c97be31bc

7
6
1

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
7
6