Burak Burak - 15 days ago 5
React JSX Question

Give className to the matched element in forEach loop with React.js

Guys i have a random word in my example and i am spliting that random word's letters to spans.

Then i check if there is specific letter in that word and use

forEach
loop to achieve this.
This is my function;

getLetter:function(e){
var val = e.currentTarget.textContent;
this.state.letters.forEach(function(letter) {
if (letter === val) {
alert("There is 'r' letter in the word.")
e.target.className = 'clicked';
letter.className='foundedLetter';
}
});


I can give class
e.target
but can't give class the matched
letter
in forEach loop.


How can i make it?

Thanks in advance.

JSFIDDLE

Answer

I changed your for-loop definition into a for of loop, to make it more clear for the eye.

    getLetter(e)
    {
        var val = e.currentTarget.textContent;

        for (let letter of this.state.letters) {
            if (letter === val) 
            {
                e.target.className = 'clicked';
                letter.className = 'foundedLetter'
            }
        }
    }

This piece of code should work, unless if the letter variable you wanna give a className to is NOT a string character.

Make sure you rendered the spans as well. you could also look at this.refs and at a reference at your span. with this you can get the DOMElement and set a className to it. I will show you how to use refs to get DOMelements:

 var MyCom = React.createClass({
  getInitialState: function() {
    return {
      random: 'lorem',
      letters:[],
      letter: ''
    }
  },
  splitLetter:function(){
   var s = this.state.random;
   for (var i = 0; i < s.length; i++) {
    this.state.letters.push(s.charAt(i));
   }
   this.setState({
   letters:this.state.letters
   })
  },
  getLetter:function(e){
   var val = e.currentTarget.textContent;
   var _this = this;
    this.state.letters.forEach(function(letter) {
     if (letter === val) {
     alert("There is 'r' letter in the word.")
     console.log(letter, val);
     e.target.className = 'clicked';
     _this.setState({letter: letter})
    }
});
  },
  render: function() {
    return (
      <div>
      <p>The word is: <strong>{this.state.random}</strong></p>
      <p>Click the button first then click the r letter below</p>
        <button onClick={this.splitLetter}>Split letter</button>
        <p>Click on: <strong><span onClick={this.getLetter}>r</span></strong></p>
      {this.state.letters.map(function(item){  
  return (
       <div>
         <span className={item == this.state.letter ? 'foundedLetter' : ''}>{item}</span>  
      </div>
       )
    },this) /*added this to map function  */
    }
    </div>
    )
  }
});

ReactDOM.render(
  <MyCom/>,
  document.getElementById("app")
)

for example: console.log(this.state.letters)

< span > H < /span > --> this you can give className

H --> this you cant give className

Comments