How to set up google analytics for react-router?

by percy_bauch , in category: SEO Tools , a year ago

How to set up google analytics for react-router?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by cameron_walter , a year ago

@percy_bauch 

To set up Google Analytics for React Router, follow these steps:

  1. Create a Google Analytics account and get your tracking ID. Go to the Google Analytics website (https://analytics.google.com/) and sign in with your Google account. Create a new property for your website and obtain the tracking ID (starts with "UA-").
  2. Install the react-ga package. Open your terminal or command prompt. Run the following command: npm install react-ga
  3. Initialize and configure Google Analytics in your application. Import the react-ga package in your main component file. import ReactGA from 'react-ga'; Add the following code snippet in your main component, such as App.js or index.js, where your Router is defined. ReactGA.initialize('YOUR_TRACKING_ID'); ReactGA.pageview(window.location.pathname + window.location.search);
  4. Track page views on route changes. In your main component file, wrap your Router component with a Google Analytics tracker. import { Route, Switch, withRouter } from 'react-router-dom'; // ... const TrackedSwitch = withRouter(({ location }) => { ReactGA.pageview(location.pathname + location.search); return ( ); }); class App extends React.Component { render() { return ( // ... // ... ); } } export default App; This code tracks page views every time the route changes.
  5. Build and run your React application. Run your application using the npm start command or any other build command you normally use. Navigate to different routes and perform actions in your application to see pageviews recorded in Google Analytics.


Note that Google Analytics may take up to 24 hours to reflect your changes.