Last active
July 7, 2019 05:45
-
-
Save moriyuu/0a4a46dbb0f002434ab1a43c97be31bc to your computer and use it in GitHub Desktop.
react-ga の pageview をページ遷移毎に発火する with react-router v4 ref: https://qiita.com/moriyuu/items/349fc02dc7e469009b6a
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment