Skip to content

Instantly share code, notes, and snippets.

@tebajanga
Created November 29, 2018 05:35
Show Gist options
  • Save tebajanga/b57e63f1a5e533ce764c98ffd1f98244 to your computer and use it in GitHub Desktop.
Save tebajanga/b57e63f1a5e533ce764c98ffd1f98244 to your computer and use it in GitHub Desktop.
Removing Specific Element in Array React
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;
@tebajanga
Copy link
Author

By using Lodash which is a modern JavaScript utility library delivering modularity, performance & extras.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment