0

I'm learning React.js and confused on the below code:

btnClick(){
    return (
        <div>
            <button onClick={alert("button clicked!")} >Click me</button>
        </div>
    )
}
render(){
    return(
        <div> 
            {this.btnClick()}
        </div>
    )
}

the alert only get prompted after refreshing every time but not when clicking. Why?

2 Answers 2

3

You should write:

<button onClick={() => alert("button clicked!")} >Click me</button>

And

{this.btnClick}

or

{() => this.btnClick()}
Sign up to request clarification or add additional context in comments.

1 Comment

The second code won't work. The right would be {this.btnClick()}. You need to call the function. Fiddle here
0

{this.btnClick()} is fine but you need to change the alert function to onClick={() => alert("button clicked!")}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.