Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created January 25, 2021 20:59
Show Gist options
  • Save sibelius/8b01b5677d6b8e4c329400e3049e03a0 to your computer and use it in GitHub Desktop.
Save sibelius/8b01b5677d6b8e4c329400e3049e03a0 to your computer and use it in GitHub Desktop.
listen to caret position of an input
const useCaretPosition = () => {
const [caret, setCaret] = useState({
selectionStart: 0,
selectionEnd: 0,
});
const onEvent = useCallback((e) => {
const input = e.target;
setCaret({
selectionStart: input.selectionStart,
selectionEnd: input.selectionEnd
});
}, []);
const events = {
onClick: onEvent,
onKeyUp: onEvent,
onFocus: onEvent,
}
return [caret, events];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment