December 7, 2022

React Example - Insert New Object in an Array

In this tutorial we'll see how to insert an object into an array of objects in your React application especially when you are storing that array in state. What you need to keep in mind is that the you should not mutate an array when you store them in state. You should rather create a new array with the required changes and set state to use this new array.

Inserting into an array - React

As stated above you need to create a new array which should contain the existing elements and then the new element at the end.

Preferred way to do it, in React, is to use spread operator to get all the existing elements and then add the new array element.

As an example, we'll have a ProductForm component to add a new Product to an array. There is also a Products component that shows the products which are in the array.

Products.js

import { Fragment } from "react";
const Products = (props) =>{
    return(
        <Fragment>
            <h2>Product List</h2>
            <ul>{
                props.products.map((product) => (
                    <li key={product.id}>
                        Id- {product.id} <br />
                        Name- {product.name}                    
                    </li>
                ))
            }
            </ul>
        </Fragment>
    );
}
export default Products;

List of products is passed to the Products component from the parent component (App.js), that is why it is accessible here through props.

ProductForm.js

import { Fragment } from "react";
import { useState } from "react";

const ProductForm = (props) => {
    const [prodName, setProdName] = useState('');
    const clickHandler = () => {
        props.onAddProduct(prodName);
        setProdName('');
    }
    return(
        <Fragment>
            <h2>Product Form</h2>
            <input
                value={prodName}
                onChange={e => setProdName(e.target.value)}
            />
            <button onClick={clickHandler}>Add Product</button>
        </Fragment>
    );
}

export default ProductForm;

Some point to note in ProductForm component-

  1. Uses useState hook to maintain the product name state.
  2. On the click of the button, clickHandler() function is called which in turn calls the onAddProduct function in another component, that is why it is called using props.

App.js

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 },
];
function App() {
  const [products, setProducts] = useState(productList);
  const addProductHandler = (productName) => {
    setProducts([
      ...products,
      { id: Math.round(Math.random() * 10), name: productName }
    ]);
  }
  return (
    <div>
      <ProductForm onAddProduct={addProductHandler}/>
      <hr />
      <Products products={products}/>

    </div>
  );
};

export default App;

Important points to note here-

  1. An array is created with some existing product objects in it.
  2. The array is stored in the state.
  3. In addProductHandler() function new array is created by adding the existing products (using spread operator) and then adding the new product object (Math.random is used to create new ID here, not an ideal way but does the job here!). This new array is then set as new state by passing it to setProducts().
    setProducts([
      ...products,
      { id: Math.round(Math.random() * 10), name: productName }
    ]);
    
  4. Reference to the addProductHandler function is passed in <ProductForm> tag as props.
    <ProductForm onAddProduct={addProductHandler}/>
    
  5. products Array is passed in Products tag as props.
    <Products products={products}/>
    

With everything done if a new product "Keyboard" is added through the form, it should be added to the products array.

That's all for the topic React Example - Insert New Object in an Array. 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