I need to set cursor (caret) to 1st position when input is focused:
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>
);
}