1

I my react class component I tried it this way. But as soon as it renders the alert popup keeps coming all the time without any button click.

onHandleOnClick(data, e) {
console.log(data);
alert("got it" + data);
  }

renderRating(){
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
return arr.map((val) => {
  return (
    <button
     
      onClick={this.onHandleOnClick(val)}
    >
      {val}
    </button>
  );
 });
};

render() {
return (
  <div>
    {this.renderRating()}
 </div>
)
}

I am new in React. How do I do it?

1
  • 1
    You're calling the function instead of assigning it to the onClick event. Instead pass an anonymous function onClick={(e) => this.onHandleOnClick(val, e)} Commented Mar 14, 2021 at 11:29

1 Answer 1

2

You're calling the function instead of assigning it to the onClick event.

Since you need to pass a parameter to the callback you can pass an anonymous function to onClick. Note that to also capture the event that React passes implicitly you should pass this as an argument in the anonymous function.

onClick={(e) => this.onHandleOnClick(val, e)}
Sign up to request clarification or add additional context in comments.

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.