Home > Software engineering >  How can I do to change the first element of an array using useState?
How can I do to change the first element of an array using useState?

Time:06-27

here is my code :

const [myArray, setMyArray] = useState([0, 0])

And I would like to change only the first element to get myArray = [3, 0]

How can I do to do that ?

Thank you very much !

CodePudding user response:

You can do in this way. First copy the state then do modification and set it again

const handleChange = () => {
  let copyState = [...myArray]
  copyState[0] = 3
  setMyArray(copyState)
} 

CodePudding user response:

You can call setMyArray method passing a function as argument. The function destructures the myArray into el1 and el2 and recreates a new array where the first element is equal to 3:

setMyArray((myArray) => {
  const [el1, el2] = myArray;
  
  return [3, el2]
});

or simplified

setMyArray(([el1, el2]) => [3, el2]);

  • Related