add to array react hooks code example
Example 1: usestate array push
setTheArray([...theArray, newElement]);
Example 2: functional component how to add to existing array react
const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray([...theArray, `Entry ${theArray.length}`]);
};
return [
<input type="button" onClick={addEntryClick} value="Add" />,
<div>{theArray.map(entry =>
<div>{entry}</div>
)}
</div>
];
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);
Example 3: add items to a react array in hooks
const addMessage = (newMessage) => setMessages(state => [...state, newMessage])
Example 4: adding to array using reach hooks
setMyArray(oldArray => [...oldArray, newElement]);
Example 5: add items to a react array in hooks
const addMessage = (newMessage) => setMessages(state => [newMessage, ...state])