add object to state array code example

Example 1: How to add object in an array using useState

import React, { useState } from 'react';
 
function App() {
 
  const [items, setItems] = useState([]);
 
  // handle click event of the button to add item
  const addMoreItem = () => {
    setItems(prevItems => [...prevItems, {
      id: prevItems.length,
      value: getRandomNumber()
    }]);
  }
 
  // generate 6 digit random number
  const getRandomNumber = () => {
    return Math.random().toString().substring(2, 8);
  }
 
  return (
    

useState with an array in React Hooks - Clue Mediator




{JSON.stringify(items, null, 2)}
); } export default App;

Example 2: add object to array setstate

To push to the beginning of the array do it this way

   this.setState( prevState => ({
     userFavorites: [{id: 3, title: 'C'}, ...prevState.userFavourites]
  }));

Example 3: push values to state array class react

this.setState(prevState => ({
  arrayvar: [...prevState.arrayvar, newelement]
}))

Tags:

Misc Example