Skip to content

Instantly share code, notes, and snippets.

@goququ
Created April 25, 2021 13:28
Show Gist options
  • Save goququ/95f479035f65e285780c0eead9cca5ab to your computer and use it in GitHub Desktop.
Save goququ/95f479035f65e285780c0eead9cca5ab to your computer and use it in GitHub Desktop.
Sync input caret
import { useState, useRef, useEffect, useCallback } from 'react';
export function useCaretPosition<
T extends HTMLInputElement | HTMLTextAreaElement = HTMLInputElement
>() {
const node = useRef<T>(null);
const [start, setStart] = useState(0);
const [end, setEnd] = useState(0);
const updateCaret = useCallback(() => {
// Get the updated caret postions from the ref passed in
if (node && node.current) {
const { selectionStart, selectionEnd } = node.current;
setStart(selectionStart!);
setEnd(selectionEnd!);
}
}, []);
useEffect(() => {
// Set the caret position by setting the selection range with the
// most current start and end values
if (node && node.current) {
node.current.setSelectionRange(start, end);
}
});
return { start, end, ref: node, updateCaret };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment