Created
November 29, 2018 05:35
-
-
Save tebajanga/b57e63f1a5e533ce764c98ffd1f98244 to your computer and use it in GitHub Desktop.
Removing Specific Element in Array React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import * as _ from 'lodash'; | |
class Content extends Component { | |
state = { | |
products: [ {id: 1, name: 'some name'}, | |
{ id: 2, name: 'some other name'}, | |
{ id: 3, name: 'some other name 2'}, | |
{ id: 4, name: 'other stuff'}, | |
{ id: 5, name: 'other stuff 1'}, | |
{ id: 6, name: 'other stuff 2'} | |
]; | |
} | |
constructor(props) { | |
super(props); | |
} | |
removeProduct(index) { | |
const products = this.state.products; | |
_.pullAt(products, index); | |
this.setState({ products: products }); | |
} | |
render() { | |
const { products } = this.state; | |
return ( | |
<div> | |
{products.map(n => { | |
return ( | |
<div key={n.id}> | |
{n.name} <button onClick={(event) => this.removeProduct(products.indexOf(n))}>remove item</button> | |
</div> | |
); | |
})} | |
</div> | |
); | |
} | |
} | |
export default Content; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By using Lodash which is a modern JavaScript utility library delivering modularity, performance & extras.