monkeyjs monkeyjs - 6 days ago 6
React JSX Question

reactjs map and css class toggle

<div>
{this.props.data.map((res, index) => {
return (<div key={index}>
<div>
<span>{response.testData}</span>
<a key={index} onClick={() => this.showExtraLine(index)}><span className={`btn-green ${this.state.showExtraLine ? 'active' : ''}`}></span></a>
{ this.state.showExtraLine ? <span>
{res.abc[0].def}
</span> : '' }
</div>
</div>
);
})}
</div>
showExtraLine(e){
this.setState({
showExtraLine: !this.state. showExtraLine,
});
}


Need to toggle the {res.abc[0].def} part on click of anchor - toggle works, but not sure how to handle toggling only the corresponding span - right now it is hiding all the rows..how to handle css toggle when using .map?

Answer

I think the problem is in your state variable, you are using a single state variable and printing the <span> on the basis of state of that variable. Instead of that use an array in state showExtraLine = [], in showExtraLine() function you are passing index, use that index to toggle only that element. Try this i should work:

{this.props.data.map((res, index) => {
  return (<div key={index}>
    <div>
      <span>{response.testData}</span>
      <a key={index} onClick={() => this.showExtraLine(index)}><span className={`btn-green ${!this.state.showExtraLine[index] ? 'active' : ''}`}></span></a>
      { !this.state.showExtraLine[index] ? 
         <span>{res.abc[0].def}</span> 
      : '' }
    </div>
  </div>
  );
})}

showExtraLine(index){
    let showExtraLine = this.state.showExtraLine;
    showExtraLine[index] = !showExtraLine[index];
    this.setState({
       showExtraLine: showExtraLine,
    });
  }
Comments