add items to a react array in hooks

Solutions on MaxInterview for add items to a react array in hooks by the best coders in the world

showing results for - "add items to a react array in hooks"
Luciana
10 May 2016
1setTheArray(currentArray => [...currentArray, newElement])
Lorenzo
04 Oct 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, {
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
Giorgio
11 Jan 2021
1setMyArray(oldArray => [...oldArray, newElement]);
2
Josefa
13 Jan 2018
1const addMessage = (newMessage) => setMessages(state => [...state, newMessage])
2
Hilary
26 Apr 2016
1setTheArray([...theArray, newElement]);
2
similar questions
queries leading to this page
add items to a react array in hooks