Reputation: 343
I'm missing something. Here's a very simple hello world, the goal is to just fire an alert event onClick. The event does fire when the page loads, but not when I click the button. I appreciate the help. Here's a jsFiddle to make it easier to see: jsFiddle
var Hello = React.createClass({
render: function() {
return <button onClick={alert("Hello World!")}>
Click Me
</button>;
}
React.render(<Hello />, document.getElementById('container'));
Upvotes: 19
Views: 69936
Reputation: 3452
Note: this is another way to do it if you want something quick/inline:
<button onClick={()=>{ alert('alert'); }}>alert</button>
Upvotes: 19
Reputation: 343
If the function to be run has parameters, is has to be bound to the function as follows:
var Hello = React.createClass({
handleClick: function (text) {
alert(text)
},
render: function () {
return <button onClick = {
this.handleClick.bind(null, "Hello World")
} > Click Me < /button>;
}
});
React.render(<Hello / > , document.getElementById('container'));
This makes sense now. Thanks again @Chris-Hawkes for pointing me in the right direction.
Upvotes: 4
Reputation: 343
Now I see why I had the problem before. The problem came when I was trying to pass an argument to the function:
var Hello = React.createClass({
myClick: function (text) {
alert(text);
},
render: function() {
return <button onClick={this.myClick("Hello world")}>
Click Me
</button>;
}
});
This has the same behavior as the original code.
Upvotes: 0
Reputation: 12430
I think you're going about this wrong, because ReactJS is just JavaScript I don't think your way of firing this event will work. Your onClick should fire a function attached to your React element like so.
var Hello = React.createClass({
myClick: function () {
alert("Hello World!");
},
render: function() {
return <button onClick={this.myClick}>
Click Me
</button>;
}
});
React.render(<Hello />, document.getElementById('container'));
Upvotes: 26