How to programmatically show the left most content of the HTML input element when the text is longer than the input itself in React

Viewed 65

I have an input element which it's value is 'abcdefghijklmnopqrstuvwxyz'

I used ref to highlight the content of 'n' to 'z'

inputRef.current.setSelectionRange(18, 26);

which result into this:

bad

How can I programmatically set the input to this instead?

enter image description here

Additional insight:

If I switch to another tab on the browser and go back to the tab containing this input, it will result in what I want, but I do not know how to make it work with code.

1 Answers

You can use the Element.scrollLeft attribute with decent browser support now, here's a Codesandbox: https://codesandbox.io/s/flamboyant-panini-02gr7l?file=/src/App.js

I've used timeouts to setup the scenario but the key part is here, and it requires a timeout since it needs to fire after the setSelectionRange call.

setTimeout(() => (ref.current.scrollLeft = 0), 100);

As with timeouts in general, the time required is a bit flaky.

Related