Member-only story
React: handling an input caret position
When we modify the text of an HTML input while the user types using React, we may see the caret jumping at the end of the text.
This happens typically when we modify the length of the text the user is typing.
In the example below, a React component is stripping away the ‘&’ illegal characters from the string ‘asd&fasfe’:
If we edit the text and try to insert an illegal character in the middle of the string, the caret will jump at the end of the text. In image below I am typing an ‘&’ in the middle of the text.
The component we are using has the following code:
Modify selectionStart and selectionEnd
At this point we could decide that we might just modify the event passed in from to our handler selectionStart
and selectionEnd
properties.
removeInvalidCharacters(event) {
const regex = /[|&;$%@"<>()+,]/g;
const text = event.target.value; if (text.match(regex)) {
event.target.selectionStart = event.target.selectionStart - 1…