React onClick and preventDefault() link refresh/redirect?
A full version of the solution will be wrapping the method upvotes inside onClick, passing e and use native e.preventDefault();
upvotes = (e, arg1, arg2, arg3 ) => {
e.preventDefault();
//do something...
}
render(){
return (<a type="simpleQuery" onClick={ e => this.upvotes(e, arg1, arg2, arg3) }>
upvote
</a>);
{
try bind(this) so your code looks like below --
<a className="upvotes" onClick={this.upvote.bind(this)}>upvote</a>
or if you are writing in es6 react component in constructor you could do this
constructor(props){
super(props);
this.upvote = this.upvote.bind(this);
}
upvote(e){ // function upvote
e.preventDefault();
return false
}
React events are actually Synthetic Events, not Native Events. As it is written here:
Event delegation: React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops.
Try to use Use Event.stopImmediatePropagation
:
upvote: (e) ->
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
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.