react-datetime
react-datetime copied to clipboard
wrong cursor position while editing input with keyboard
I'm having this problem when i select a date like "11/22/2020 10:07" , and then when i want to delete the month and change it with keyboard , when i delete the first number (here 1), the cursor jumpes to the end of the input text (here after 7), and its so annoying, any idea how to fix this?? this happens only if i use it as controlled input!!
I have this issue since upgrading from 2.16.3 to 3.0.4. It makes entering a date and time via keyboard impossible. The only working case is now to select a single digit and press a keyboard key to replace it. Delete+insert isn't possible anymore.
This is also blocking us from upgrading to v3.
Same problem even with version 2.16.3. If I remove zeros from the year cursor jumps to the end of input.
any solution? i find this solution on other platform hope can help u guys
onChange(event) {
const caret = event.target.selectionStart
const element = event.target
window.requestAnimationFrame(() => {
element.selectionStart = caret
element.selectionEnd = caret
})
// your code
}
ho-hey! any updates on this?
Same here... But here is a workaround:
const inputElement = useRef(null);
const [cursorPosition, setCursorPosition] = useState(0);
useEffect(() => {
inputElement.current.setSelectionRange(cursorPosition, cursorPosition);
}, [currentValue, cursorPosition]);
const onInput = () => setCursorPosition(inputElement.current.selectionStart);
return (
<Datetime
inputProps={{
onInput,
ref: inputElement,
}}
value={currentValue}
/>
);
+1 for this.
@obrejla
This causes the field to focus when value is changed on Safari, because Safari focuses to whatever had its selection changed.
Seems like its better to only change selection if the element is already focused:
useEffect(() => {
if (inputElement.current === document.activeElement) {
inputElement.current.setSelectionRange(cursorPosition, cursorPosition);
}
}, [currentValue, cursorPosition]);
Still facing this problem in v3.1.1 and the solution above worked for me. This is the custom hook version used by myself:
function useInputProps(value: string) {
const inputRef = useRef<HTMLInputElement>(null)
const [cursorPosition, setCursorPosition] = useState(0)
useEffect(() => {
if (inputRef.current !== document.activeElement) return
inputRef.current!.setSelectionRange(cursorPosition, cursorPosition)
}, [value, cursorPosition])
return {
inputRef,
onInput: () => setCursorPosition(inputRef.current!.selectionStart!),
}
}
function Component() {
...
const { inputRef, onInput } = useInputProps(value)
return (
<Datetime
inputProps={{
ref: inputRef,
onInput,
}}
value={value}
/>
)
}