How does react know where to put the cursor while typing inside an input element?

Viewed 92

If I write this in a component:

const [value, setValue] = useState("");
....
return <input onChange={(e) => setValue(e.target.value)} value={value} />

Then react somehow knows how to preserve the cursor position. I'm wondering - how does react do this exactly? All react knows is that I'm resetting the value of the input. Is there some sort of algorithm to find the added letter and add the cursor in at the right place?

1 Answers

Nothing special needs to be done.

The target value has been reassigned by the user by the time the React change callback runs; that's why the setValue(e.target.value) sets the new value in state, rather than the old value.

When the value is assigned to an input, if the new value is the same as the old value, the browser will not change the cursor position. Demo:

const input = document.querySelector('input');
input.addEventListener('input', (e) => {
  console.log('change seen');
  input.value = input.value;
});
<input>

Related