Search code examples
reactjsreact-routerreact-bootstrapreact-componentreact-class-based-component

Condition in React Class to modify style


enter image description here

--> DEMO CODE <--

I'm trying to make when the word is found the word inside the TIP popup is crossed out.

Code when is word is found

  verifyFindWord = (words) => {
for (let word of words) {
  let lettersSelected = this.getLetterSelectedSameWord(word);

  if (lettersSelected == word.length) {
    alert("You find the word: " + word);
  }
}

};

I created this css code and it shows all the crossed out words, and the idea is if the word is found this word should be crossed out automatically.

<div className="words">
                  {words.map((word, index) => (
                    <span
                      key={word + index}
                      className={word ? "finded" : ""}
                    >
                      {word}
                      <br />
                    </span>
                  ))}
                </div>

Solution

  • In the <span> tag the className value must consider the existence of word in a list of found words. For example, with findedWords.includes(word):

    <div className="words">
        { words.map((word, index) => (
            <span key={word + index}
                  className={this.state.findedWords.includes(word) ? "finded" : ""}>
                {word}<br />
            </span>
        ))}
    </div>
    

    So, in the verifyFindWord function you pre-populate the findedWords list:

    verifyFindWord = words => {
        for (let word of words) {
            let lettersSelected =
                this.getLetterSelectedSameWord(word);
    
            if (lettersSelected == word.length) {
                alert("You find the word: " + word);
                const findedWords = this.state.findedWords;
                findedWords.push(word);
                this.setState({ findedWords });
            }
        }
    }