A nice and simple option that worked for me was:
<a href="javascript: false" onClick={this.handlerName}>Click Me</a>
This is because those handlers do not preserve scope. From react documentation: react documentation
Check the "no autobinding" section. You should write the handler like: onClick = () => {}
If you are using React Router, I'd suggest looking into the react-router-bootstrap library which has a handy component LinkContainer. This component prevents default page reload so you don't have to deal with the event.
In your case it could look something like:
import { LinkContainer } from 'react-router-bootstrap';
<LinkContainer to={givePathHere}>
<span className="upvotes" onClick={this.upvote}>upvote</span>
</LinkContainer>
I didn't find any of the mentioned options to be correct or work for me when I came to this page. They did give me ideas to test things out and I found that this worked for me.
dontGoToLink(e) {
e.preventDefault();
}
render() {
return (<a href="test.com" onClick={this.dontGoToLink} />});
}
render: ->
<a className="upvotes" onClick={(e) => {this.upvote(e); }}>upvote</a>
In a context like this
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
As you can see, you have to call preventDefault() explicitly. I think that this docs, could be helpful.