Member-only story

React: handling an input caret position

Alberto De Natale
3 min readDec 13, 2020

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…

--

--

Alberto De Natale
Alberto De Natale

Written by Alberto De Natale

Alberto De Natale is a passionate tech-enthusiast software developer.

No responses yet