Eran Abir
Eran Abir

Reputation: 1097

React - Render Item inside map function by click event

let say i have an array with two items i want to make a click event that will show some content for the specific index i 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 it will show two items i want to click on the first item button and showing the hidden content only under the same item index and not for all the items

how can i do that

thanks alot !

Upvotes: 4

Views: 14427

Answers (1)

philraj
philraj

Reputation: 841

<button onClick={() => this.showContent(index)}>Show Content</button>

This is the general idea. You need to pass the index of the item to your click handler. In your click handler, you can either do something which will edit the items in the array themselves, setting a showContent boolean as one of their properties, and then use it like this...

this.array.map((item, index) => {
   return (
      <div>
         {item.name}
         <button onClick={() => this.showContent(index)}>Show Content</button>
         {item.showContent &&
            this.renderContent()
         }
      </div>
   );
})

...or you can maintain a mapping from item ID to content visibility, and reference it when rendering:

constructor(props) {
  super(props);

  this.state = {
    isItemContentVisible: {}
  };
}

showContent(id) {
  // merge new value with existing visibility status into new object
  this.setState({
    isItemContentVisible: {     
      ...this.state.isItemContentVisible,
      [id]: true
    }
  });
}

// ...and when you're rendering the list...
this.array.map((item, index) => {
   return (
      <div>
         {item.name}
         <button onClick={() => this.showContent(item.id)}>Show Content</button>
         {this.state.isItemContentVisible[item.id] &&
            this.renderContent()
         }
      </div>
   );
})

Upvotes: 3

Related Questions