Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created September 19, 2019 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/0a187f9a59a09e11c8942dfebc7e7fda to your computer and use it in GitHub Desktop.
Save ryanflorence/0a187f9a59a09e11c8942dfebc7e7fda to your computer and use it in GitHub Desktop.
// 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