facebook / react

The library for web and native user interfaces.

Home Page:https://react.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug: Controlled state input weird behavior when state update is postponed to the next micro task

yf-yang opened this issue · comments

React version: v18.3

Steps To Reproduce

  1. Open the codesandbox link below
  2. Add characters in the middle of each input
  3. 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?

 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);
      }
    });
  };

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.