React :why do the alert message is displayed before i click

class Button extends React.Component {

state = {  }

render() {

    return (

        <>

          <button onClick={alert(this.props.button1)}>click me</button>

        </>

    );

}

}

export default Button;

You are invoking (calling) the function.

If you want to pass arguments to a handler you have to either wrap it in an anonymous function or write a named function and use that.

Inline anonymous function:

<button onClick={() => alert(this.props.button1)}>click me</button>

Named handler:

function handleButtonClick() {
  alert(this.props.button1);
}

<button onClick={handleButtonClick}>click me</button>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.