Respond to onClick event

I'm missing something. Here's a very simple hello world, the goal is to simply fire an alert onClick event. The event fires when the page loads, but not when the button is pressed. I appreciate the help. Here's jsFiddle to make browsing easier: jsFiddle

var Hello = React.createClass({ render: function() { return <button onClick={alert("Hello World!")}> Click Me </button>; } React.render(<Hello />, document.getElementById('container')); 
+6
source share
4 answers

I think you are going to do it wrong, because ReactJS is just JavaScript. I don’t think your way of triggering this event will work. Your onClick should run a function attached to your React element like this.

 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')); 
+12
source

Note: this is another way to do this if you want something fast / inline:

 <button onClick={()=>{ alert('alert'); }}>alert</button> 
+7
source

If the function to be launched has parameters, it must 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')); 

Now that makes sense. Thanks again @ Chris-Hawkes for pointing me in the right direction.

+2
source

Now I understand why I had a problem before. The problem arose when I tried to pass an argument to a function:

 var Hello = React.createClass({ myClick: function (text) { alert(text); }, render: function() { return <button onClick={this.myClick("Hello world")}> Click Me </button>; } }); 

This is the same behavior as the source code.

0
source

All Articles