Reputation: 372
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
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