Skip to content
Advertisement

Is it okay to call onClick on an anchor tag in ReactJS

Folks,

I have an anchor tag inside my component like so:

JavaScript

I want to call an analytics function when user clicks on this tag like so:

JavaScript

Notice that I’m not setting state or calling any of the react functions. Is it okay if I just call a function on the onClick event of the anchor tag? Something like this:

JavaScript

with

JavaScript

Is there a better way to do this? Since as soon as the redirection happens the component unmount is called and I’m not sure my onClick handler will be called or not. Am I thinking something wrong?

Advertisement

Answer

You should create your own element with a span for example :

JavaScript

Apply the same styling to it using CSS (or inline CSS if this is a quick fix) :

JavaScript

And then change your page in the function you showed us :

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement