19

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'));

4 Answers 4

26

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'));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Chris-Hawkes, that works. I had tried something similar before, but that sent me down the wrong path. Thanks again
This React code doesn't seem to work in Codepen in 2018. I changed React.render to ReactDOM.render, but still no button shows up on the page.
19

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

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

1 Comment

OnClick would keep alerting whenever I loaded the page. instead of doing onClick={thisFunc()} just do onClick={() => thisFunc}
4

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.