'How to add items to array in react

Code:

export default function App() {
  const [name,setName] = useState("");
  var myArray = [];
  const handleAdd = () => {
    myArray = [...myArray,name]
    setName("")
  }
  return (
    <div className="App">
      <input placeholder="type a name" onChange={(e) => setName(e.target.value)}/>
      <button onClick={handleAdd}>add</button> 
      <button onClick={() => console.log(myArray)}>test</button>
      {myArray.map((n) => {
        return <h2>{n}</h2> 
      })}
    </div>
  );
}

OnClick it isn't adding the name to the array.



Solution 1:[1]

this is how you "push" to an array with useState

const [array, setArray] = useState([])
setArray(previous => [...previuous, newItem])

Solution 2:[2]

You should use a state for your array and set that state to see the changes reflected:

export default function App() {
    const [name, setName] = useState('');
    const [myArray, setMyArray] = useState([]);
    const handleAdd = () => {
        setMyArray([...myArray, name]);
        setName('');
    };
    return (
        <div className="App">
            <input
                placeholder="type a name"
                onChange={(e) => setName(e.target.value)}
            />
            <button onClick={handleAdd}>add</button>
            <button onClick={() => console.log(myArray)}>test</button>
            {myArray.map((n) => {
                return <h2>{n}</h2>;
            })}
        </div>
    );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 c0dm1tu
Solution 2 Aneesh