user8292330
user8292330

Reputation:

onclick not firing in react

I am very new to react and I stuck on some idea. The problem I have is that onclick is not firing up.

class Application extends React.Component{
    render () {
        return (
            <div>
                <button onClick={alert("hello world")}>Hello Application</button>
            </div>
        )
    }  
}

ReactDOM.render(<Application />,document.getElementById("tar"));

I am expecting when the button is clicked, alert saying hello world will be show up. However, that is not happening! Why is that?

Upvotes: 3

Views: 17901

Answers (4)

Etherealm
Etherealm

Reputation: 2484

You need to bind the onclick button

class Application extends React.Component{
render(){
    return(
      <div>
        <button onClick={() => alert("hello world")}>Hello Application</button>
      </div>
    )
  }  
}

ReactDOM.render(<Application />,document.getElementById("tar"));

Upvotes: 1

Artem Mirchenko
Artem Mirchenko

Reputation: 2170

Because you put alert as object instead as mthod to be completed, you nedd to wrap your alert in function or method of the class. Try this code:

class Application extends React.Component{
 render(){
  return(
    <div>
     <button onClick={() => alert("hello world")}>Hello Application</button>

  </div>

  )
 }  

}

ReactDOM.render(<Application />,document.getElementById("tar"));

Upvotes: 1

Kaps
Kaps

Reputation: 189

onClick will run function supplied to it. if you will do

 onClick={() => alert("hello world")} /** es6 **/

or

onClick={function() { alert("hello world"); }}

Upvotes: 1

Kyle Richardson
Kyle Richardson

Reputation: 5645

You are invoking the alert() when assigning it to the onClick event of the button.

Try wrapping it in an es6 arrow function.

<button onClick={() => { alert("hello world")} }>Hello Application</button>

Or better still.. make it a method on the component that you pass as the handler to the button like this:

class Application extends React.Component {
    constructor( props ) {
        super( props );

        // since you're using this method in a callback, don't forget to
        // bind the this context
        this.handleClick = this.handleClick.bind( this );
    }

    handleClick() {
        alert( "hello world" );
    }

    render(){
        return(
            <div>
                <button onClick={ this.handleClick }>Hello Application</button>

                </div>
        );
    }
}

Upvotes: 5

Related Questions