Reputation: 51
I have built a rock/paper/scissors React app. The app works fine but I just would like to add a feature.
When the user or the CPU wins, I would like to add a specific class (.bigger) to that specific element that won.
For instance, in the following piece of code, I am trying to add the .bigger class when the user wins by selecting paper, but the app crashes.
if(this.state.victory === true) {
if(this.state.choiceName === "paper") {
document.getElementById("paper-box").classList.add("bigger")
}
}
I get the following error: "Cannot read property 'classList' of null". Why is that so? And how can I achieve what I want ?
Thank you very much in advance.
https://codesandbox.io/s/lively-smoke-7z7ej?file=/src/components/Main.js
Upvotes: 0
Views: 129
Reputation: 944084
The likely reason (you didn't include a mcve in the question itself) is that you haven't rendered the element with that ID at the time you are searching the DOM for it.
In general, when working with React, you should not access the DOM directly.
Your render function should be responsible for determining the output.
...
<span id="paper-box" className={ this.state.choiceName === "paper" ? "bigger" : "" }>
...
Upvotes: 2