@react-awesome/use-selection-range
Version:
useSelectionRange tracks the input selection range.
34 lines (33 loc) • 995 B
JavaScript
import { useState, useEffect } from "react";
const useSelectionRange = (inputEl, { initialPosition = { start: 0, end: 0 } } = {}) => {
const [caret, setCaret] = useState({
start: initialPosition.start,
end: initialPosition.end
});
useEffect(() => {
if (!inputEl)
return;
const onKeyDown = (e) => {
setTimeout(() => {
if (e.target && "selectionStart" in e.target && "selectionEnd" in e.target && typeof e.target.selectionStart === "number" && typeof e.target.selectionEnd === "number") {
setCaret({
start: e.target.selectionStart,
end: e.target.selectionEnd
});
}
}, 0);
};
inputEl.addEventListener("keydown", onKeyDown);
inputEl.addEventListener("click", onKeyDown);
return () => {
inputEl.removeEventListener("keydown", onKeyDown);
inputEl.removeEventListener("click", onKeyDown);
};
}, [inputEl]);
return {
caret
};
};
export {
useSelectionRange
};