December 13, 2022

React Example - Remove Object From an Array of Objects

If you want to remove an object from an array of objects in your React application best option is to use filter method which filters out the item that has to be removed and returns a new array containing rest of the elements. Since a new array is returned by filter method so you don't mutate the state rather you set state to this new array.

Remove object from an array of objects using filter

With in the filter method, provide a function that runs for each array element. With in that function, you'll have to write the condition, each array element is tested against that condition, if it passes the condition it is added to the new array otherwise not.

As an example, let's have a shopping cart with certain products added. With each listed product there is also a delete button to remove that product from the list.

There are two components; Products and ProductItem

Products.js

import { Fragment, useState } from "react";
import ProductItem from "./ProductItem";
const productList = [
    { id: 1, name: 'Laptop', price: 455.50 },
    { id: 2, name: 'Mouse', price: 15.89 },
    { id: 3, name: 'USB', price: 10.00 },
    { id: 4, name: 'HDD', price: 55.50 },
  ];
const Products = (props) =>{
    const [products, setProducts] = useState(productList);
    const removeProduct = (id) => {
        setProducts(products.filter((product) => product.id !== id));
    }
    return(
        <Fragment>
            <h2>Product List</h2>
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Price</th>
                    </tr>
                </thead>
                <tbody>
                {
                    products.map((product) => (
                        <ProductItem key={product.id} id={product.id} 
                        name={product.name} price={product.price} onRemoveHandler={removeProduct}/>                  
                    ))
                }
                </tbody>
            </table>
        </Fragment>
    );
}

export default Products;
Important points to note in the code are-
  1. Array is initialized with some product objects. This array is then set as the initial state with in the useState hook.
  2. Array is iterated using map method, in each iteration <ProductItem> component is called with some props data.
  3. removeProduct function gets the id of the product which has to be removed and uses filter method to filter out the specific product. New array created by filter method is then pass to the setProducts() method to update state.

ProductItem.js

This component renders each product as one table row and a delete button with each product.

const ProductItem = (props) => {
    const onClickHandler = () => {
        props.onRemoveHandler(props.id);
    }
    return (
        <tr>
            <td>{props.name}</td>
            <td>{props.price}</td>
            <td><button onClick={onClickHandler}>Delete</button></td>
        </tr>
    )
}

export default ProductItem;

That's all for the topic React Example - Remove Object From an Array of Objects. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment