I was making a form and had a component with an onClick event. When placing the cursor in an input field in the form and pressing enter, the onClick event of the other component fires. Feels very random.
Am I doing something wrong or is this an actual bug?
This jsbin illustrates the problem: http://jsbin.com/motuso/2/edit?js,console,output
It may be a bug. What's happening is because you have a button in a form, the default type is 'submit'. So it's a bug if the spec doesn't say to emit a click event on the submit button when a form is submitted. Otherwise it's just one of many DOM quirks.
CS -> JS, tabs -> spaces, and 0.11 -> 0.13pre: http://jsbin.com/zipilezuqu/3/edit
Add type="button"
to props to solve it.
Button = React.createClass
render: ->
React.DOM.button
onClick: @onClick
@props.children
type: 'button'
Yep, that solves it. Thanks!
I do not know if it is similar, I have this code in my JSX:
<button onClick={localStorage.removeItem("localData")}>Clear Local Storage</button>
It appears that this fires always, not if i click. Whenever I refresh the page, the "localData" disappears from the localStorage (without hitting the button).
I noticed that if I do this (in ES6), it works:
<button onClick={() => localStorage.removeItem("localData")}>Clear Local Storage</button>
Is this a bug OR expected? And if expected, why?
Thanks.
Expected. The former is equivalent to
var handler = localStorage.removeItem("localData");
<button onClick={handler}>Clear Local Storage</button>
Note that the removeItem
call runs immediately upon render, _not_ when you click the button. You want to pass a function that gets called instead. You can do this with an arrow function (as you saw), a regular function like onClick={function() { localStorage.removeItem("localData"); }}
, or a method like onClick={this._removeData}
.
Excellent explanation, thank you!
how to do this in coffeescript? what is the equivalent syntax for this?
Most helpful comment
Expected. The former is equivalent to
Note that the
removeItem
call runs immediately upon render, _not_ when you click the button. You want to pass a function that gets called instead. You can do this with an arrow function (as you saw), a regular function likeonClick={function() { localStorage.removeItem("localData"); }}
, or a method likeonClick={this._removeData}
.