react push to array code example

Example 1: add new array at the back of react state

this.setState(prevState => ({
  myArray: [...prevState.myArray, "new value"]
}))

Example 2: add new array at the back of react state

this.setState(prevState => ({
  myArray: ["new value", ...prevState.myArray]
}))

Example 3: react state array push

how to add array data on state react
this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array

Example 4: 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 5: add new array at the back of react state

this.setState(prevState => ({
  myArray: [ {"name": "object"}, ...prevState.myArray]
}))

Tags:

Misc Example