Folks,
I have an anchor tag inside my component like so:
JavaScript
x
9
1
class myComponent {
2
3
render () {
4
return (
5
<a href="/link/to/other/page">Link</a>
6
);
7
}
8
}
9
I want to call an analytics function when user clicks on this tag like so:
JavaScript
1
2
1
analytics.submitData({event: "page redirection"});
2
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
1
4
1
anchorClickHandler() {
2
analytics.submitData({event: "page redirection"});
3
}
4
with
JavaScript
1
2
1
<a href="/link/to/other/page" onClick={this.anchorClickHandler.bind(this)}>Link</a>
2
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
1
2
1
<span className='sub' onClick={this.anchorClickHandler}>Link</span>
2
Apply the same styling to it using CSS (or inline CSS if this is a quick fix) :
JavaScript
1
5
1
.sub {
2
cursor: pointer,
3
color: blue
4
}
5
And then change your page in the function you showed us :
JavaScript
1
6
1
anchorClickHandler = event => {
2
analytics.submitData({event: "page redirection"});
3
// Navigate to /link/to/other/page
4
window.location.href = '/link/to/other/page';
5
}
6