0

I am new to react and working on a legacy codebase. Am wondering if we can write a global button click handler for click tracking.

The jQuery equivalent of this would be something like,

utilities.js :

 var subscribeForClickTracking = function() {
        $( "button" ).click((event) => { console.log($(event.target).html()) })
        $( "p" ).click((event) => { console.log($(event.target).html()) })
  }

In all the html files, will add reference to utiliies.js and this snippet of code.

$(document).ready(function () {
 subscribeForClickTracking();
});

I have surfed about this and reached similar so questions, like Higher Order React Component for Click Tracking and https://www.freecodecamp.org/news/how-to-track-user-interactions-in-your-react-app-b82f0bc4c7ff/

But these solutions involve modifying the button's implementation, which would lead to huge change. (For a html form with 50+ buttons).

Is there an alternate approach to achieve something similar to the above jQuery approach.

Thanks in advance.

Raghav
  • 2,890
  • 7
  • 36
  • 56

1 Answers1

1

No, you can not do that. The reason is that React prevents you from doing global things to avoid side effects. I think the proper React way would be to create your own Button component.

First create a new component : export default Button = (props) => <button ...props /> Then, you can import and use Button instead of button in any component. Then in your Button component, you can override your onClick method like this :

    <button
    ...props
    onClick={() => {
    // doWhatYouWantHere;
    props.onClick()
    />

However, as React is JavaScript, you can still use vanilla JavaScript to attach an event to every button

Thibaut
  • 84
  • 5