Answers for "add object to array react hook"

5

React Hooks append state

setTheArray(currentArray => [...currentArray, newElement])
Posted by: Guest on November-07-2020
0

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 (
    <div classname="App">
      <h3>useState with an array in React Hooks - <a href="https://www.cluemediator.com">Clue Mediator</a></h3>
      <br>
      <button onclick="{addMoreItem}">Add More</button>
      <br><br>
      <label>Output:</label>
      <pre>{JSON.stringify(items, null, 2)}</pre>
    </div>
  );
}
 
export default App;
Posted by: Guest on December-13-2020
14

usestate array push

setTheArray([...theArray, newElement]);
Posted by: Guest on June-02-2020
0

add object to array react hook

setTheArray([...theArray, newElement]);
Posted by: Guest on December-29-2020

Code answers related to "add object to array react hook"

Code answers related to "Javascript"

Browse Popular Code Answers by Language