0

Im trying to add an event listener to a button so when its pressed it can add a value into a container.

<div className="grid-container">
            <div>
            <button id="redBet" className="redButton" onclick={this.handleBetsRed}>Place Red</button>
            <div id="redSearch" class="ui search">
              <input class="prompt" type="text" placeholder="Common passwords..." />
                <div class="results">
                  <p className="para"></p>
                </div>
                </div>
            </div>

The Button is inside the above code with the onclick to run the function below:

handleBetsRed = () => {
    document.getElementsByClassName("redButton").addEventListener("click", () => {
      console.log("Yeet")
    })
  
  }

this function is not inside any function and right above the render, return statements.

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
  • 2
    `getElementsByClassName()` returns a nodeList not a single element. – Randy Casburn Oct 16 '20 at 00:29
  • 1
    Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – evolutionxbox Oct 16 '20 at 00:32
  • 1
    Consider not using querySelector at all when using react. It’s not necessary. Use a ref instead. – evolutionxbox Oct 16 '20 at 00:34

2 Answers2

-1

replace onclick with onClick in the redButton, and remove the getElementsByClassName from the click handler function

<div className="grid-container">
  <div>
    <button id="redBet" className="redButton" onClick={this.handleBetsRed}>Place Red</button>
    <div id="redSearch" class="ui search">
      <input class="prompt" type="text" placeholder="Common passwords..." />
        <div class="results">
          <p className="para"></p>
        </div>
    </div>
  </div>
</div>
handleBetsRed = () => {
  console.log("Yeet")
}
Marik Ishtar
  • 2,899
  • 1
  • 13
  • 27
-1

there are two issues,

1:

document.getElementsByClassName("redButton")

Here, getElementsByClassName returns HTMLCollection containing matched Nodes, Not a single on. So, U probably wanna do something like this,

document.getElementsByClassName("redButton")[0]

Or, U may use querySelector,

document.querySelector(".redButton")

2:

 <button id="redBet" className="redButton" onclick={this.handleBetsRed}>Place Red</button>

Here, onclick did u mean onClick

ezio4df
  • 3,541
  • 6
  • 16
  • 31