You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

withTracker.jsx 952B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * From ReactGA Community Wiki Page https://github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker
  3. */
  4. import React, { Component } from 'react';
  5. import ReactGA from '../../src';
  6. export default function withTracker(WrappedComponent, options = {}) {
  7. const trackPage = (page) => {
  8. ReactGA.set({
  9. page,
  10. ...options
  11. });
  12. ReactGA.pageview(page);
  13. };
  14. const HOC = class extends Component {
  15. componentDidMount() {
  16. const {
  17. location: { pathname: page }
  18. } = this.props;
  19. trackPage(page);
  20. }
  21. // eslint-disable-next-line camelcase
  22. UNSAFE_componentWillReceiveProps(nextProps) {
  23. const {
  24. location: { pathname: currentPage }
  25. } = this.props;
  26. const nextPage = nextProps.location.pathname;
  27. if (currentPage !== nextPage) {
  28. trackPage(nextPage);
  29. }
  30. }
  31. render() {
  32. return <WrappedComponent {...this.props} />;
  33. }
  34. };
  35. return HOC;
  36. }