I'm rendering a link with react:
render: -> `<a className="upvotes" onClick={this.upvote}>upvote</a>`
Then, above I have the upvote function:
upvote: -> // do stuff (ajax)
Before link I had span in that place but I need to switch to link and here's the trouble - every time I click on .upvotes
the page gets refreshed, what I've tried so far:
event.preventDefault() - not working.
upvote: (e) -> e.preventDefault() // do stuff (ajax)
event.stopPropagation() - not working.
upvote: (e) -> e.stopPropagation() // do stuff (ajax)
return false - not working.
upvote: (e) -> // do stuff (ajax) return false
I've also tried all of the above using jQuery in my index.html, but nothing seems to work. What should I do here and what I'm doing wrong? I've checked event.type and it's click
so I guess I should be able to avoid redirect somehow?
Excuse me, I'm a rookie when it comes to React.
Thank you!
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
1. Memoization using useMemo() and UseCallback() Hooks. Memoization enables your code to re-render components only if there's a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.
The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed.
stopPropagation prevents further propagation of the current event in the capturing and bubbling phases. preventDefault prevents the default action the browser makes on that event.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With