Tom
Tom

Reputation: 179

React Cursor jumping when formatting textfield

I know there are a lot of topics on this, and I've done my best reading and implementing their solutions, but I just cant get it to work properly

Im trying to format the phone number so that it displays in a certain format.

I created a demo of how it works in my app. https://codesandbox.io/s/dank-leaf-94s3w?file=/src/App.js

Edit: sorry to describe the issue a bit more.

everything works fine when you are just typing out a # front to back

but when I try to modify the middle numbers the cursor will jump to the end after each input.

Thanks

Upvotes: 2

Views: 2761

Answers (2)

Emad Emami
Emad Emami

Reputation: 6629

You are passing the ref into the wrong element. In @material-ui/core/TextField you must pass the ref to the inputProps instead of direct ref.

Just change the:

ref={input}

to:

inputProps={{ ref: input }}

There are other issues in your code such as not parsing the value to the normal string state but the issue for jumping was for ref

Upvotes: 1

Domino987
Domino987

Reputation: 8804

Hi so the problem is that you pass a new value and that will be just like inputing the whole value. And this will cause the cursor to move to the end.

You can overcome it by requesting a window animation frame and move the cursor back to where it was:

const caret = target.selectionStart;
    const element = target;
    window.requestAnimationFrame(() => {
      element.selectionStart = caret;
      element.selectionEnd = caret;
    });

Here is a copy of your sandbox.

Upvotes: 4

Related Questions