Input loses focus when conditionally rerendering other divs
See original GitHub issueI’ve set up this JS fiddle to demonstrate the behavior I’m seeing.
Basically when I render this code:
<section>
{ phone && !App.isValidPhoneNumber(phone) ? <div>Invalid Phone Number</div> : null }
<input value={phone} onInput={this.linkState('phone')} />
{ /* Weird: if you remove the line below, there's no error... */ }
<div>Phone: {phone}</div>
</section>
As soon as the state changes such that the first line’s condition becomes true, the input loses focus. Is this a bug or expected behavior?
Update: Added GIF to illustrate behavior.
Update 2: I’ve noticed a pattern now, that this only happens if there’s two other elements of the same type. e.g. if there’s two div
tags (like in the example above), this doesn’t happen if one of them is changes to a strong
tag, but happens again if both are. Wondering if it’s some sort of recycling issue…? Still not sure why it would affect the input.
Issue Analytics
- State:
- Created 7 years ago
- Comments:20 (10 by maintainers)
Top Results From Across the Web
React.js - input losing focus when rerendering - Stack Overflow
When a re-rendering occurs, if the same key is seen, this will tell React don't clobber and regenerate the view, instead reuse. Then...
Read more >[Solved]-React.js - input losing focus when rerendering-Reactjs
The loss of focus happens because the component prop uses React.createElement each time instead of just re-rendering the changes. Details here: https:// ...
Read more >Initializing focus state in React: you might be doing it wrong
In terms of conditional rendering, you can hide or show elements, but not mount or unmount them from the DOM. And crucially, you...
Read more >React.Js - Input Losing Focus When Rerendering - ADocLib
There are a lot of different ways to autofocus a text input in React. When an input loses focus, a blur event is...
Read more >FAQs | React Hook Form - Simple React forms validation
This approach reduces the amount of re-rendering that occurs due to a user typing in input or other form values changing at the...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Confirmed this is fixed in Preact 8! 😊
Interesting. I am happy keys fixes this, but I want to better understand why the diff is removing an element there. Will be looking into it 😃