Tracking a user on your webpage has numerous benefits. For example, tracking provides insights into how a user interacts with your webpage, indicating which components of your UI are the most and least often used.
Declarative tracking is a method of tracking the interactions of a user on a webpage. Traditionally, we use the DOM to track all user interactions, however, the evolution of the component-based framework has enabled us to use component-based tracking in our applications.
One library for declarative tracking in React is react-tracking, which implements tracking for each component of the page. You can use Hooks and decorators to declare tracking on events like click events, states, functional components, class components, and more. Additionally, you can compartmentalize tracking concerns to individual components, avoiding leaking across the entire app.
In this article, we’ll look into declarative tracking using the react-tracking library. To follow along with this article, you should be familiar with React and React Hooks. Let’s get started!
We can break down react-tracking into three main components. For one, trigger
kickstarts the tracking process and can be a click
event, loading
event, etc. Essentially, trigger
is the interaction of the user with the element in the application.
component
is the component that we are tracking. Usually, component
refers to forms, cards, etc. You can track functional as well as class-based components. All tracking data will be wrapped inside the dispatch
component and will be displayed in the console when triggered. If you don’t define the dispatch
component, the tracking data will be pushed to window.dataLayer[]
, which is ideal for Google Analytics.
With these three components, we can use react-tracking to track any component in our application. Let’s see it in action by running through an example.
click
buttonAs an example, we’ll use a click
button that tracks a functional component as well as a class component.
First, let’s set up up the environment required to get started with react-tracking. We’ll use VS Code as our code editor, which is powerful and includes extensions to help you write better code. If you’re familiar with a different code editor, feel free to use that instead.
To install react-tracking, we first need to install React. We’ll create a small program that will track the button click
event in a functional and class component. The class
button will also track the number of clicks.
First, we’ll install React as follows:
npm init react-app my-app
With React installed, we can install the react-tracking library. Run the command below:
npm install --save react-tracking
With React and react-tracking installed, we’ll go ahead and get started with our code.
We’ll need to import the following elements from react-tracking:
React
useTracking
: Used as a Hook to track any eventtrack
: Used to track class
and member
functions with the @
decorator and dispatch all the tracking data to the consoleImport the items above with the command below:
import track, { useTracking } from "react-tracking"; import React from "react";
The functional component will contain the useTracking()
Hook, which is used to track the click
button
event. useTracking()
then dispatches button click data to the console.
Below, we have an onClick
event function for the button that contains trackEvent
. Here, you can pass the message that you want to display in the console, which we’ll add later:
const HookButton = () => { const {trackEvent} = useTracking() return ( <div> <h2>Click for HookButton</h2> <button onClick={()=> trackEvent({funComponent:'HookButton', event: "HookButton-Clicked"})}>Click Me!</button> </div> ); }
class
componentIn the class
component, we’ll track the button click
event along with the number of clicks. To track the class
component, we’ll use track
, followed by the message we’ll set.
In class
, we have a state to count the number of clicks. In return, we’ve rendered a button with the click
event linked to the handleClick
function.
We’ve also tracked the member function of the class with track
. We have an arrow function with the state as props to pass the value of numClicked
. In the handleClick
function, we have increased the state value of numClicked
by 1
each time the button is clicked:
@track({class:'ClassButton'}) class ClassButton extends React.Component{ state = { numClicked : 1 }; @track((props, state) =>({event:'ClassButton-Clicked', clickCount:state.numClicked})) handleClick = () => { this.setState({ numClicked: this.state.numClicked + 1 }) } render(){ return( <div> <h2>Click for ClassButton</h2> <button onClick={this.handleClick}>Click Me!</button> </div> ) } }
App
componentNow, we’ll wrap the HookButton
functional component and the ClassButton
class component in the App
component:
const App = () =>{ return( <div className="App"> <h1>React-Tracking</h1> <HookButton /> <ClassButton /> </div> ) }
dispatch
componentThe dispatch
component is a functional component that will render in the console when triggered. You can add your own message to dispatch
like Component: "Apps"
. dispatch
uses track
to display the content that we define inside it in the console.
We’ll also use dispatch
to dispatch all the data we collected into the console, followed by the component that you want to render on the page. Next, we just need to export the functional component that contains the track logs:
const TrackedApp = track( { Component: "Apps" }, { dispatch: data => { console.log(data); } } )(App); export default TrackedApp
The output of the code above is as follows:
You can find tracking details in the console when you click the button.
HookButton
click output:
{app: "my-app", funComponent: "HookButton", event: "HookButton-Clicked"}
ClassButton
click output:
{app: "my-app", class: "ClassButton", event: "ClassButton-Clicked", clickCount: 1}
clickCount
will increase as you continue clicking the button. You can find the code and experiment with it in the CodeSandbox:
In this tutorial, we explored react-tracking, which does a pretty good job of tracking all events and providing important details in the console. We created a program to track the click button
event and show the tracking data on each click. The @
decorator, along with track
, can track most of the data in React, including data in props and state.
You can use the steps in this tutorial to track different components and classes in your application. I hope you’ll consider react-tracking in your next project. Thanks for reading, and be sure to leave a comment if you have any questions.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]