Reputation:
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?
Upvotes: 0
Views: 1061
Reputation: 59511
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]
Upvotes: 1