-
Notifications
You must be signed in to change notification settings - Fork 49.7k
Description
I am working on a component that has a controlled input element. The component has an onChange handler that manipulates user input before setting the value back on the input's value prop. As a result of this manipulation, the caret position as restored by React may be different than where the user was typing.
To control this situation, I keep track of the caret position in the component's state:
onKeyUp({ target }) { // also in `onChange`, `onMouseUp`, etc
this.saveSelectState(target);
}
and then set it back to the desired position after the component updates:
componentDidUpdate() {
const { selectionStart, selectionEnd } = this.state;
const { input } = this.refs;
try {
if (input === document.activeElement) {
input.setSelectionRange(selectionStart, selectionEnd);
}
} catch(e) {}
}
The API I desire, however, would be more like:
<input
type='text'
selectionStart={ 5 }
selectionEnd={ 5 }
... and so on
/>
It was pretty simple to implement this abstraction for myself, but it seems like something that's actually missing from React. I think this goes along well with the idea that React is an API for declaratively controlling UI components' state.