Track events in React with Google Analytics
Today we’ll show you how to track events in React with Google Analytics. In the previous article, we have explained about the integration of the Google Analytics in React application.
Here, we will go one step further than Google Analytics integration. We will track the user behaviors with the help of the events in React app.
Demo Application
Steps to track events in React with Google Analytics
1. Integrate Google Analytics
In the first step, we will have a startup react application using the create-react-app
and integrate Google Analytics with the help of the react-ga
package. We will recommend you to check the following article for integration.
How to add Google Analytics to the React App
Hope you understand the integration and now we will slightly update the same example to track the user activity.
2. Update page to handle the events
In the second step, we will simply update the home page named App.js
to track events. For that, we will add two different buttons and handle the click events.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import React, { Component } from 'react'; class App extends Component { // handle GitHub button click handleGitHub = () => { } // handle StackBlitz button click handleStackBlitz = () => { } render() { return <div> <h4>Home</h4> <p>This is the Home page.</p> <input type="button" value="Download GitHub Source" onClick={this.handleGitHub}></input> <input type="button" value="StackBlitz Project" onClick={this.handleStackBlitz} style={{ marginLeft: 15 }}></input> </div> } } export default App; |
3. Track events
So far, we have integrated Google Analytics and updated the design to track events. Now, we have to call the event
method from the button click. Check the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import React, { Component } from 'react'; import ReactGA from 'react-ga'; class App extends Component { // handle GitHub button click handleGitHub = () => { ReactGA.event({ category: 'Links', action: 'GitHub', label: 'GitHub button clicked!', value: 1 }); } // handle StackBlitz button click handleStackBlitz = () => { ReactGA.event({ category: 'Links', action: 'StackBlitz', label: 'StackBlitz button clicked!', value: 1 }); } render() { return <div> ... ... </div> } } export default App; |
The following arguments are used to manage the events.
- category – Name of the category to group the events.
- action – A description of the behaviour.
- label – Details description related to the action.
- value – Pass the integer value against the event.
Click here to find more information about the event’s arguments.
4. Output
Run the react application and check the output.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂
Very Nice Article, Keep posting!