0

I want to pass the innerHTML of a clicked button to the onClick method in React. How can I do that? Please note, I am not asking about the arrow notation; I am asking how to get the innerHTML of the button so that I can pass it as an argument.

This is how I am creating the buttons:

var buttons = [];
  for (let i = 0; i < 4; i++) {
    buttons.push(
      <button onClick={() => props.handleClick(this.correctAnswers, this.innerHTML)}>
        {currentAnswers[i]}
      </button>
    )
  }
        return <div >{buttons}</div>;}

and this is my onClick method

 handleClick(correctAnswers, inner) {
   alert(correctAnswers)
   alert(inner)

 }

The handleClick() doesn't do anything yet. I'm just trying to pass in the values for now. alert(inner) is undefined. Thanks

HGamble
  • 385
  • 4
  • 16
  • 1
    While this is possible to fix by using a `function` instead, and saving the `this` context from the outer scope with something like `that = this`, referencing the clicked element's `innerHTML` directly in the handler is pretty weird to do - referencing `currentAnswers[i]` would make more sense, to start with, eg ``() => props.handleClick(this.correctAnswers, currentAnswers[i])`` – CertainPerformance Jun 16 '19 at 04:12
  • OK. Thanks. That makes sense. – HGamble Jun 16 '19 at 04:19
  • It worked perfectly. Thanks. Can you remove the "duplicate" from this post? Thanks. – HGamble Jun 16 '19 at 04:24
  • It *is* a duplicate. You're using an arrow function when you wanted to capture the new `this` context – CertainPerformance Jun 16 '19 at 05:16
  • The `onClick` passes the event itself, so: ` – Meir Jun 16 '19 at 05:24
  • No. Those are completely different questions. I wasn't asking about the arrow function or about this. I was asking about using the innerHTML of a button as an argument. – HGamble Jun 16 '19 at 07:45

0 Answers0