cbdeveloper
cbdeveloper

Reputation: 31335

Set cursor position when input is onFocus?

I need to set cursor (caret) to 1st position when input is focused:

CodeSandbox

I guess the following code should be working, but it's not. It works if it's triggered by a button click, though.

What am I doing wrong?

import React, { ChangeEventHandler, useRef, useState } from "react";

const setCaretPosition = (ctrl, pos) => {
  // Modern browsers
  if (ctrl.setSelectionRange) {
    ctrl.focus();
    ctrl.setSelectionRange(pos, pos);
  }
};

export default function App() {
  
  const [value,setValue] = useState("123456789");
  const input_ref = useRef(null);

  const onFocus = () => {
    setCaretPosition(input_ref.current, 0);
  };

  const onChange = (event) => {
    setValue(event.target.value);
  };

  const buttonClick = () => {
    setCaretPosition(input_ref.current, 0);
  };

  return (
    <React.Fragment>
      <div>
        <input 
          type="text" 
          onChange={onChange} 
          value={value} 
          ref={input_ref}
          onFocus={onFocus}
        />
        <button onClick={buttonClick}>Reset cursor</button>
      </div>
    </React.Fragment>
  );
}

Upvotes: 4

Views: 2715

Answers (1)

Pavan
Pavan

Reputation: 858

The actual issue with onFocus not with your code it seems that your code put the cursor at beginning and then focus event puts it back to end. So postponing your code firing after focus puts the cursor at end resolves the issue.

I tried to put it in setTimeout, it started working right away. - Tested with your code sandbox

setTimeout(() => {
      setCaretPosition(input_ref.current as HTMLInputElement, 0);
})

Upvotes: 3

Related Questions