Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onClick event

Tags:

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'));
like image 374
Ivan Histand Avatar asked Sep 09 '15 17:09

Ivan Histand


People also ask

How do you get onClick event in React?

React events are written in camelCase syntax: onClick instead of onclick . React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()" .

What is handleClick in React?

In the Toggle class, a handleClick method is defined as an instance method, which changes the local state. In the render method, this. handleClick is passed to the button as an event handler. Finally, do not forget to bind this to handleClick in the constructor.


2 Answers

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'));
like image 113
Chris Hawkes Avatar answered Sep 28 '22 11:09

Chris Hawkes


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

<button onClick={()=>{ alert('alert'); }}>alert</button>
like image 28
armyofda12mnkeys Avatar answered Sep 28 '22 11:09

armyofda12mnkeys