React: Inputs are deselected when firing callback in onChange

Created on 26 Nov 2015  路  4Comments  路  Source: facebook/react

I am having an issue with text based inputs in React 0.14.3 and React DOM 0.14.3. When the onChange event is fired for an input, the input will be deselected.

Here is what this looks like in the UI:
wtf

Here is an example JSBin of my components.

There is a <Form /> top-level component, which describes the fields on the form. This component also holds the state of the form and is the only component that extends React.Component. For each field in the form, there is a <Field /> child component鈥攚hich each has a <Label /> and <Input /> child. The form also has one <Submit /> component, which, when clicked, will fire an onSubmit function with the state of the form. With the exception of <Form />, these components are all stateless functional components.

The <Input /> components are controlled. They get their value from the top level form component. The state is properly updated in this top level after the onChange event is fired鈥攁s you would expect things to typically work with a controlled form. This state is then passed down via props to the input.

I've been trying to figure out what could possibly be the cause of this weird deselection issue, but haven't made any progress... any ideas? Thanks.

Most helpful comment

This causes it:

key={`${Math.random()}-${caseSafeFieldName}`}

On every render the key is a different random value. When the key is different, then React will not reuse the old component. So you lose focus because the input got replaced.

All 4 comments

This causes it:

key={`${Math.random()}-${caseSafeFieldName}`}

On every render the key is a different random value. When the key is different, then React will not reuse the old component. So you lose focus because the input got replaced.

Ah, right, that would make sense. Bad mistake! Thanks.

Math.random() as a key is definitely a bad idea 馃檴

Haha, yes. I have long sense moved away from this solution. 馃槻

Was this page helpful?
0 / 5 - 0 ratings