Bug: Controlled state input weird behavior when state update is postponed to the next micro task
yf-yang opened this issue · comments
yf-yang commented
React version: v18.3
Steps To Reproduce
- Open the codesandbox link below
- Add characters in the middle of each input
- The first input works as expected. In the second input, the cursor will instantly jump to the end, also input methods will not work.
Link to code example: https://codesandbox.io/p/sandbox/74mhkd
The current behavior
By adding an additional queueMicrotask to the second input, two inputs behavior are different.
The expected behavior
Work loop stuff should not affect DOM manipulation.
Is it a bug or feature? Is it a react stuff?
Mistry Aakash commented
const handleSecondChange = (event) => {
const value = event.target.value;
setSecondInput(value);
// Set cursor position after state update <--
requestAnimationFrame(() => {
if (secondInputRef.current) {
secondInputRef.current.setSelectionRange(value.length, value.length);
}
});
};
yf-yang commented
Thanks @akshdev1998, unfortunately it is off topic and the issue is not for seeking solution of making an input component work correctly from a component user's perspective.