0

How do you update the value inside an array with the useState hook after i used it in a map function?

At the moment i have a handleChange function which works but i want to use the setState() directly inside the onChange in the input field.

const [array, setArray] = useState([1,2,3]);

{array.map((v,i) => {<input onChange={(e)=>setArray([...array, ...v, e.target.value])}/>})}

How do i update the value like this?

1 Answer 1

1

I'd advice against it, because such a one-liner makes the code quite unreadable, in my opinion.

Anyway, here it is...

{array.map((v,i) => {
  <input onChange={
    (e)=>setArray(
      [...array.slice(0, i), e.target.value, ...array.slice(i+1)]
    )}
  />
})}

Given the array [1,2,3,4,5] and i=2 you will have:

  • ...array.slice(0, i)[1,2]
  • e.target.value → the new value
  • ...array.slice(i+1)[4,5]
Sign up to request clarification or add additional context in comments.

1 Comment

So it's not possible to change the value without slicing? Like we do with an object using the spread operator and then assigning new value to the property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.