Sarkis
Sarkis

Reputation: 372

Using Splice to delete desired elment onClick in Reactjs

I have an array of colors and after picking a color from the array; I want to be able to delete any selected colour onClick(). I cant seem to delete the one I want because I have set it like splice(index, 1). Any suggestions?

state = {
    colors: [],
    name: [],
    front: 'https://homepages.cae.wisc.edu/~ece533/images/boat.png',
    back: 'https://homepages.cae.wisc.edu/~ece533/images/fruits.png'
  };

  deleteColor(color) {
    let colors = [...this.state.colors.slice()]
    const index = colors.findIndex(
      x => x.value === color.value
    )
    colors.splice(index, 1)
    this.setState({ colors: colors })
    console.log('Deleted')
  }


Then in the return block

<div
key={color.id}
 onClick={e => {
 e.stopPropagation()
 e.preventDefault()
 this.deleteColor(color)
}}
>
      //something
</div>

I would like to delete any element onClick(). Thanks!

Upvotes: 0

Views: 85

Answers (1)

Timofey Goncharov
Timofey Goncharov

Reputation: 1148

You can make it all easier.

deleteColor = (color) => (e) {
  e.stopPropagation()
  e.preventDefault()
  this.setState({ colors: this.state.colors.filter((el) => el.value !== color.value) })
}
<div
 key={color.id}
 onClick={this.deleteColor(color)}
>
      //something
</div>

Upvotes: 2

Related Questions