I'm trying to update (onchange) the state in an array of objects, but I'm losing the input focus every time that I type something.
Any idea why this is happening?
Here is a Sandbox: https://codesandbox.io/s/inspiring-booth-636tx
{stagesState.map(stage => {
return (
<div key={uuidv4()}>
<input
type="text"
onChange={e => {
const name = e.target.value;
setStagesState(currentStage =>
currentStage.map(x =>
x.id === stage.id ? { ...x, name } : x
)
);
}}
value={stage.name || ""}
/>
</div>
);
})}
This how my data looks:
[
{
name: "First Stage",
},
{
name: "Second Stage",
},
{
name: "Third Stage",
}
];
This is because of key defined using uuidv4
. Every render react is not able to identify if the input is new or old in array. So it loses focus. Use id
as key instead of uuidv4
and it will work just fine.
{stagesState.map(stage => {
return (
<div key={stage.id}>
<input
type="text"
onChange={e => {
const name = e.target.value;
setStagesState(currentStage =>
currentStage.map(x =>
x.id === stage.id ? { ...x, name } : x
)
);
}}
value={stage.name || ""}
/>
</div>
);
})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With