0

I used map function for an array in states. I have gave them an index and I want to when they are clicked, Remove from the array. I have written the code below but It will remove all indexes except the item was clicked :) This is my code :

removeFromList(x) {
    this.setState({
        allTasks: this.state.allTasks.splice(x, 1)
    });
}

And :

this.state.allTasks.map((task, index) => {
    return <li key={ index } onClick={ () => this.removeFromList(index) }>{ task }</li>;
})
  • it's because splice returns deleted value – guijob Feb 26 '18 at 21:45
  • @guijob :\ So how should I remove that ? –  Feb 26 '18 at 21:45
  • @Herohtar I'm with you ... –  Feb 26 '18 at 21:46
  • just call: `removeFromList(x) { this.state.allTasks.splice(x, 1); }` and your allTasks will be the same except by removed element – guijob Feb 26 '18 at 21:48
  • You could use `.filter()`... something like `.filter((item, index) => index !== x)` should give you back an array of everything except for the one at the specified index. – Herohtar Feb 26 '18 at 21:49
  • @guijob It doesn't work because I need to rerender the ui so I called this.setState –  Feb 26 '18 at 21:49
  • @Herohtar I changed to this but not worked : ``` removeFromList(x) { this.setState({ allTasks: this.state.allTasks.filter(e => e !== x) }); } ``` –  Feb 26 '18 at 21:51
  • 1
    @Ali you are comparing elements instead of indexes in this approach, use second arg of filter – guijob Feb 26 '18 at 21:52
  • 1
    @AliBahaari The first parameter is the actual item, you need to include the second parameter to get the index. So `this.state.allTasks.filter((e, i) => i !== x) })` – Herohtar Feb 26 '18 at 21:55
  • 1
    @Herohtar Works like a charm ... Thanks for both of you ... –  Feb 26 '18 at 21:59

0 Answers0