How to integrate React with Google Analytics?
@aniyah.green
To integrate React with Google Analytics, you can follow these steps:
1 2 3 |
npm install react-ga # or yarn add react-ga |
1 2 3 4 5 6 |
import ReactGA from 'react-ga'; // Initialize Google Analytics ReactGA.initialize('YOUR_GA_TRACKING_ID'); export default ReactGA; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import ReactGA from './analytics'; function App() { // Track page view on component mount useEffect(() => { ReactGA.pageview(window.location.pathname); }, []); return ( <div> {/* Your app content */} </div> ); } export default App; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import ReactGA from './analytics'; function SomeComponent() { const handleClick = () => { // Track button click event ReactGA.event({ category: 'Button', action: 'Click', label: 'Button Label', }); }; return ( <button onClick={handleClick}>Click Me</button> ); } |
Remember to replace 'YOUR_GA_TRACKING_ID'
in step 2 with your actual Google Analytics Tracking ID. With these steps, you should be able to integrate React with Google Analytics and start tracking page views and events in your application.