Created
September 19, 2019 23:44
-
-
Save ryanflorence/0a187f9a59a09e11c8942dfebc7e7fda to your computer and use it in GitHub Desktop.
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
// Before | |
class TrackPageViews extends React.Component { | |
componentDidMount() { | |
this.track() | |
} | |
componentDidUpdate(prevProps) { | |
if (prevProps.location !== this.props.location) { | |
this.track() | |
} | |
} | |
track() { | |
ga.send(["pageview", this.props.location.pathname]) | |
} | |
render() { | |
return null | |
} | |
} | |
function App() { | |
return ( | |
<React.Fragment> | |
<Route | |
render={({ location }) => ( | |
<TrackPageViews location={location} /> | |
)} | |
/> | |
<Switch>{/* your routes */}</Switch> | |
</React.Fragment> | |
) | |
} | |
// After | |
function usePageViews() { | |
const location = useLocation() | |
useEffect(() => { | |
ga.send(['pageview', location.pathname]) | |
}, [location]) | |
} | |
function App() { | |
usePageViews() | |
return ( | |
<Switch>{/* your routes */}</Switch> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment