React OnClick And PreventDefault() Link Refresh/redirect?
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!
Answer
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();
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?