add object to array react hook

Solutions on MaxInterview for add object to array react hook by the best coders in the world

showing results for - "add object to array react hook"
Isidora
14 Oct 2017
1setTheArray(currentArray => [...currentArray, newElement])
Mattia
22 May 2018
1import React, { useState } from 'react';
2 
3function App() {
4 
5  const [items, setItems] = useState([]);
6 
7  // handle click event of the button to add item
8  const addMoreItem = () => {
9    setItems(prevItems => [...prevItems, {
10      id: prevItems.length,
11      value: getRandomNumber()
12    }]);
13  }
14 
15  // generate 6 digit random number
16  const getRandomNumber = () => {
17    return Math.random().toString().substring(2, 8);
18  }
19 
20  return (
21    <div classname="App">
22      <h3>useState with an array in React Hooks - <a href="https://www.cluemediator.com">Clue Mediator</a></h3>
23      <br>
24      <button onclick="{addMoreItem}">Add More</button>
25      <br><br>
26      <label>Output:</label>
27      <pre>{JSON.stringify(items, null, 2)}</pre>
28    </div>
29  );
30}
31 
32export default App;
33
Ilian
01 Jun 2018
1setTheArray([...theArray, newElement]);
Alejandro
03 Apr 2017
1setTheArray([...theArray, newElement]);
2
similar questions
queries leading to this page
add object to array react hook