onclick not firing in react

Tags: ,



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?

Answer

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


Source: stackoverflow