The react.js documentation describes how a text
field can be used as a controlled field and indicates that the following code can be used to
limit the maximum length of the field to 140 characters.
That is true but react.js falls to correctly manage the cursor position. That position will match
the user input until the 140 character is reached. At that point, the cursor will jump to
the end of the field. Evidently react.js only leaves the selection untouched so long as the
html is not actually impacted by the handleChange function. This can be made even clearer by adding
toUpperCase to force the field contents to always be uppercase. The cursor position then jumps to
the end of the field on every keystroke.
This issue is referenced by several GitHub tickets 12, StackOverflow discussions 12, etc.
As far as I can determine, none of these provide a functional solution.
One approach is to explicitly manage the selection
This editor is designed for Canadians, dropping any ‘a’s that are entered.
This works as expected and there are no visual artifacts.
Extending the above example so the string manipulation is provided by the web server
This works. However; when entering an ‘a’ there is a noticeable artifact as the cursor jumps to the end
and then returns to the correct position.
It has been suggested that the change should be made to a parent state and allow the child to be re-rendered,
but that does not improve matters.
The implementation is thus suboptimal but still useful.