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
Hi Mohammad! I'd suggest you to use the right formatting for the code in your posts so it's easier to read. Give me a second while I figure this out and help you out
Emmanuel Villalobos
Senior Software Developer
Ok, what you're trying to achieve is to basically "toggle" items in the array, right?
I'd suggest you to try this: In your
ddddmethod (Awful name btw):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, }) }Hope it helps!