Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lost input focus when trying to update an array of objects in React Hooks

Tags:

reactjs

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",
  }
];

like image 880
Alfrex92 Avatar asked Oct 18 '25 00:10

Alfrex92


1 Answers

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>
        );
      })}
like image 113
tarzen chugh Avatar answered Oct 20 '25 16:10

tarzen chugh