Enable google analytics with react-router

One way of doing this is to create your own Router class, which extends the one from the framework; and inside this Router class you put in the tracking logic:

class MyRouteComponent extends React.Component<Props, State> {

    constructor(props: Props) {
        super(props);
        this.state = {currentUserRefreshed: false};

        if (isProdEnv()) {
            ReactGA.initialize('UA-GOOGLE-ANAYLTICS-ID');
        }
    }

    trackPage(pageUrl:string) {
        ReactGA.set({page: pageUrl});
        ReactGA.pageview(pageUrl);
    }

    toPageUrl(location: Location) {
        return location.pathname + location.search;
    }

    componentDidMount() {
        this.props.refreshCurrentUser();

        if(isProdEnv() && this.props.location){
            this.trackPage(this.toPageUrl(this.props.location!));
        }
    }

    render() {
        ...
    }
}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.