reactjs - React - Render Item inside map function by click event -
let have array 2 items want make click event show content specific index clicked
for example :
let array = [ {name:test}, {name:test2} ] this.array.map((item,index)=>{ return( <div> {item.name} <button onclick={()=>this.showcontentfunction()} >show content</button> {this.rendercontent()} </div> ) })
now show 2 items want click on first item button , showing hidden content under same item index , not items
how can
thanks alot !
<button onclick={() => this.showcontentfunction(index)}>show content</button>
this general idea. need pass index of item click handler. in click handler, can either edit items in array themselves, setting showcontent
boolean 1 of properties, , use this...
this.array.map((item,index)=>{ return( <div> {item.name} <button onclick={() => this.showcontentfunction(index)}>show content</button> {item.showcontent && this.rendercontent() } </div> ) })
...or can maintain mapping item id content visibility, , reference when rendering:
constructor(props) { super(props); this.state = { itemcontentisvisible: {} } } showcontentfunction(index) { // merge new value existing visibility status new object const itemcontentisvisible = { ...this.state.itemcontentisvisible, [index]: true }; this.setstate({ itemcontentisvisible }); } // ...and when you're rendering list... this.array.map((item,index)=>{ return( <div> {item.name} <button onclick={()=>this.showcontentfunction()} >show content</button> {this.state.itemcontentisvisible[item.id] && this.rendercontent() } </div> ) })
Comments
Post a Comment