Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inputs are deselected when firing callback in onChange #5554

Closed
pburtchaell opened this issue Nov 26, 2015 · 4 comments · May be fixed by jackromo888/react#344, luke7oaks/react#42, xotik33/react#92, AlexanderGrovnes/react#134 or CVSpook/react#121

Comments

@pburtchaell
Copy link

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—which 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—as 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.

@waldreiter
Copy link
Contributor

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.

@pburtchaell
Copy link
Author

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

@MathieuDebit
Copy link

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

@pburtchaell
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment