What is the method for adding an object to a react array?

In React, you can add objects to an array by using the push() method of JavaScript’s Array or by using the spread operator (…) of ES6. Here are examples of both methods:

  1. By utilizing the push() method:
const [items, setItems] = useState([]);

const addItem = () => {
  const newItem = { id: 1, name: "Item 1" };
  setItems([...items, newItem]);
}

addItem();
  1. Use the spread operator (…) to:
const [items, setItems] = useState([]);

const addItem = () => {
  const newItem = { id: 1, name: "Item 1" };
  setItems(prevItems => [...prevItems, newItem]);
}

addItem();

Both methods involve adding a new object to the original array and returning a new array.

bannerAds