@larissa
To use Google Analytics with React.js, you first need to create a Google Analytics account and get a tracking ID. Once you have the tracking ID, you can integrate Google Analytics into your React.js application by following these steps:
- Install the react-ga package by running the following command in your terminal:
- Import react-ga in your main component or App.js file:
1
|
import ReactGA from 'react-ga';
|
- Initialize Google Analytics with your tracking ID in your main component or App.js file. You can do this in the componentDidMount lifecycle method:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class App extends React.Component {
componentDidMount() {
ReactGA.initialize('YOUR_TRACKING_ID');
}
render() {
return (
// Your app content
);
}
}
export default App;
|
- You can then use react-ga to send events to Google Analytics from anywhere in your application. For example, you can track page views by calling ReactGA.pageview() in the componentDidMount method of your components:
1
2
3
|
componentDidMount() {
ReactGA.pageview(window.location.pathname + window.location.search);
}
|
- You can also track custom events by calling ReactGA.event():
1
2
3
4
|
ReactGA.event({
category: 'User',
action: 'Logged In'
});
|
- Finally, make sure to build and deploy your application so that the Google Analytics tracking code is included in the production build. You can then view and analyze the data in your Google Analytics account.
By following these steps, you can easily integrate Google Analytics into your React.js application and track user interactions and behaviors.