Home > OS >  Input loses focus after I type
Input loses focus after I type

Time:12-18

I have two problem:

  1. Input loses focus after I type into the input
  2. I get an error in console saying that I need to have a unique key for renderFields, which I have unique key! I have loaded the code here: https://codesandbox.io/s/autumn-cookies-qkzfz

Thanks in advance for your answers.

CodePudding user response:

The 2 issues are closely related.

Error 1. is occurring as you key in your components is a randomly generated uuid (specifically key={uuidv4()}).

The reason this is causing the inputs to lose focus is because every time a change occurs to one the inputs you update state, which will re-render the component with a new key (as uuidv4() gets run again).

When this happens React doesn't know the user is still typing in the same component, as the keys are different (as a new UUID has been generated) so it can't correctly identify which component had focus.

You can fix this with using a consistent key. If your fields have an id, use that. Having a consistent unique, key will prevent the input from losing focus.

To remove the warning, ensure all your returns have a unique key. Right now only the case for text has a key prop. Add keys to the other possible cases and the error will go away.

Also you switch has a default: break - rather return null here then not have a return for each possible outcome of switch.

  • Related