how to add object in an array using usestate

Solutions on MaxInterview for how to add object in an array using usestate by the best coders in the world

showing results for - "how to add object in an array using usestate"
Lukas
20 Jan 2020
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, {      id: prevItems.length,      value: getRandomNumber()    }]);
10  }
11 
12  // generate 6 digit random number
13  const getRandomNumber = () => {
14    return Math.random().toString().substring(2, 8);
15  }
16 
17  return (
18    <div classname="App">
19      <h3>useState with an array in React Hooks - <a href="https://www.cluemediator.com">Clue Mediator</a></h3>
20      <br>
21      <button onclick="{addMoreItem}">Add More</button>
22      <br><br>
23      <label>Output:</label>
24      <pre>{JSON.stringify(items, null, 2)}</pre>
25    </div>
26  );
27}
28 
29export default App;
30
similar questions