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

Tags: ,


I have an anchor tag inside my component like so:

class myComponent {

    render () {
        return (
            <a href="/link/to/other/page">Link</a>

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

analytics.submitData({event: "page redirection"});

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:

anchorClickHandler() {
    analytics.submitData({event: "page redirection"});


<a href="/link/to/other/page" onClick={this.anchorClickHandler.bind(this)}>Link</a>

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?


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

<span className='sub' onClick={this.anchorClickHandler}>Link</span>

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

.sub {
    cursor: pointer,
    color: blue

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

anchorClickHandler = event => {
    analytics.submitData({event: "page redirection"});
    // Navigate to /link/to/other/page
    window.location.href = '/link/to/other/page';

Source: stackoverflow