Created
April 25, 2021 13:28
-
-
Save goququ/95f479035f65e285780c0eead9cca5ab to your computer and use it in GitHub Desktop.
Sync input caret
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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