There are two tormenting questions:

  1. There is a piece of render code

    var data = this.props.data; var hidden = this.state.hidden; var template = data.map(function(item,index) { return( <div className="mainDiv" key="{index}"> <p className="feedText">{item.author}</p> <p className={'feedText ' + 'smallmargin'}>{item.text}</p> <p className={'feedText ' + 'smallmargin ' + (hidden ? '' : 'hidden')}>{item.bigtext}</p> </div> ) }); 

    The reaction refuses to render because {index} is used twice, it must be unique, but the index value is different - 0 and 1. How to be in this situation?

  2. How to tie event? There is an event

     divClick : function(e) { e.preventDefault(); this.setState({hidden : true}); } 

    Banal onclick says divClick undefined

     <div className="mainDiv" onClick={this.divClick}> 

What are the problems?

  • 2
    Different questions should be asked in different questions;) - Dmitriy Simushev
  • onClick = {this.divClick.bind (this)} or onClick = {:: this.divClick} will not solve the problem? - arnage Nov.
  • @arnage. Of course no. It's like writing undefined.bind (this) - Duck Learns to Take Cover

1 answer 1

For question 1 , this is your typo:

You wrote:

 key="{index}" 

Accordingly, the key becomes a string. Curly brackets inside a string in jsx are just curly braces, something inside them is not a js expression.

It is necessary:

 key={index} 

Well, or key = {index.toString()} if you need the string directly (no, you don't need it)

For question 2 , when used properly, should work.
Give the entire component code. That is, the whole piece in which does not work, entirely. My crystal ball suggests that you lose context (this) in the .map method
Try this:

 var template = data.map(function(item,index) {/** где-то здесь мы вызываем this.divClick **/}.bind(this)) 

More information about the context can be read for example in the answers to this question .

  • Thats it! Your crystal ball worked. Thank you so much! It was really sealed with the object, but of course I didn’t think about bind (this). Thanks again - Lorchel