Search code examples
javascriptarraysnode.jsreactjsnodes

How to add/remove from reactjs element in onClick event


I can add array of object element by using onClick event. However, I need to remove array of object by using same onClick event.

state = {
  listofdata: []
}

dddd = (data) => {
  const d = [...this.state.listofdata]
  const t = d.push(data)

  this.setState({
    listofdata: d
  })
}

<div className="col-md-6">
  {data.map((item) => (<ul><li key={item.name} onClick={() => this.dddd(item)}><span className="plus">+</span>{item.name}</li></ul>))}
</div>

Here is my code , when I click on button , i can add array item , but i remove array item by using onClick event


Solution

  • Thanks everyone. This is answer of toggle elements . 
    you can add and remove clicking same button 
    dddd = (selectedItem) => {
      const { listofdata } = this.state;
    
      const newList = [ ...listofdata ];
    
      const itemIndex = newList.findIndex(item => item.name === selectedItem.name);
    
      if (itemIndex > -1) {
        newList.splice(itemIndex, 1);
      } else {
        newList.push(selectedItem);
      }
    
      this.setState({
        listofdata: newList,
      })
    }