0

I use ReactJS in order to make an input box which automatically takes care letter-to-letter substitutions (so that users do not need to add a specific language to their OS in order to type in that language).

The input uses JS to transform all letters from their English to their Greek equivalent using a simple substitution matrix.

The problem is that preventDefault() (which I use in order to prevent the original letter from appearing) is also preventing my input from automatically scrolling to current-cursor-position.

Is there a way to programmatically scroll my input to the current cursor position? Any alternatives?

Here is a JSFiddle which illustrates the problem:

https://jsfiddle.net/sgouros/mnzw56s9/

substituteKey = event => {
    let letterToAdd = this.ÎșeySubstitutions[event.keyCode];
    event.target.value += letterToAdd;
    this.handleOnChange(event);
    // the following line prevents input from scrolling
    event.preventDefault();
};

To reproduce:

  1. Type letters until input fills up. No scrolling takes place
  2. Press 'a' (deliberately left out of the substitutions). The input scrolls as expected (preventDefault is deliberately not being called for letter 'a' for illustration purposes)
sgouros
  • 494
  • 4
  • 9

1 Answers1

1

It seems that I have to focus on my input and then scroll to the left for as long as the scroll width is. For ex:

handleKeyDown = event => {
    if (this.ÎșeySubstitutions[event.keyCode]) {
      // this calls preventDefault() 
      // but we will fix in a bit it by manually scrolling the input
      this.substituteKey(event);
    }

    // SOLUTION: these 2 lines manually scroll the input
    // be sure to add ref="myInput" when rendering your input
    this.refs.myInput.focus();
    this.refs.myInput.scrollLeft = this.refs.myInput.scrollWidth;
  };

Many thanks to https://stackoverflow.com/users/2533679/stephen-kaiser who answered a very similar question here: "Scroll" to the very right of a long text input

sgouros
  • 494
  • 4
  • 9