Ask questionsBug: cursor jumps to end of controlled <input> tag when value is modified

React version: 16.13.1

Steps To Reproduce

  1. Make an <input> tag controlled, by setting its value in response to onChange
  2. Apply a transformation to the value (for example, replace spaces with underscores)
  3. Move cursor to the middle of the text and edit it

Link to code example:

Adapted from CodePen example ( on

The current behavior

If the transformation changes the value, the cursor is moved to the end of the input.

The expected behavior

Cursor should remain at the original position if possible (this is the behaviour of the TextInput component in React Native).


Answer questions vkurchatkin

Is this something that could/should be added as default behavior for the <input> component?

I think it is a bit against React philosophy. React is about making DOM transformations declarative, not about changing how it works. If you need such behaviour, you can make your own <Input/> component which does just that (or more).

The example in the documentation would benefit from this.

I agree, there probably should be a warning in the docs explaining that it's not as _ straightforward_ to modify input this way.

If you modify your handleChange function to the following, it should work as expected.

No, your modified code is strictly equivalent to original code. What you can't do is use the event object asynchronously, including setState(() => ...) form, without calling e.persist().


Related questions

Disable react strict mode on third party libraries hot 6
Refs - &#34;object is not extensible&#34; hot 4
Warning: Unknown DOM property for. Did you mean htmlFor? hot 4
React@16.9 block `javascript:void(0);` hot 4
TypeError: Object(...) is not a function hot 3
Warning: validateDOMNesting(...): <tr> cannot appear as a child of <table> hot 3
React custom hook "Should have a queue. This is likely a bug in React" error message. hot 2
useEffect causes 'callback is not a function' exception hot 2
DevTools: Updating state or props in devtools does not trigger component update. hot 2
Infinite loop in useEffect using blank object or array hot 2
False-positive security precaution warning (`javascript:` URLs) hot 2
Hooks API - hook breaks when exported from module hot 2
Function components do not support contextType. hot 2
Feedback on useEffect depndencies change error hot 2
[ESLint] Feedback for 'exhaustive-deps' lint rule hot 2
Github User Rank List