Cal
Cal

Reputation: 125

how to move cursor/caret to end of input when clicked in react

When the input is selected and a user has typed in it, currently if the click back on their text the cursor jumps to where they clicked. any letters typed after this appear where the cursor clicked.

what i'm trying to achieve is, when a user clicks anywhere in the input I want to have the cursor jump to the end of the input's text.

I'm using react and the react-autosize-input package.

Thanks

Upvotes: 5

Views: 2705

Answers (1)

lissettdm
lissettdm

Reputation: 13080

You can set the cursor position with HTMLInputElement.setSelectionRange() and with the input value length.

  const handleClick = (event) => {
     const {value} = event.target;
     const position = value.length;
     event.target.setSelectionRange(position, position);
  }

Upvotes: 6

Related Questions