darth-coder
darth-coder

Reputation: 762

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

Folks,

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"});
}

with

<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?

Upvotes: 2

Views: 7838

Answers (3)

kishore kingmaker
kishore kingmaker

Reputation: 476

Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing.

These values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a <button> instead. In general you should only use an anchor for navigation using a proper URL.

Upvotes: 1

Treycos
Treycos

Reputation: 7492

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';
}

Upvotes: 4

Giang Le
Giang Le

Reputation: 7054

It's is ok when call onClick on anchor tag.To prevent redirect when click on anchor tag you just call event.preventDefault()

anchorClickHandler(event) {
    event.preventDefault()
    analytics.submitData({event: "page redirection"});
    window.location.href = event.target.getAttribute('href');
}

Upvotes: 2

Related Questions