A hook for getting the state of your current text selection
npm install @brwarner/use-text-selectiontsx
import { useRef } from 'react'
import { useTextSelection } from 'use-text-selection'
export const AutoComplete = () => {
const { clientRect, isCollapsed } = useTextSelection()
// to constrain text selection events to an element
// just add the element as a an argument like useTextSelection(myElement)
if (clientRect == null) return null
return (
style={{
left: clientRect.x,
top: clientRect.y + clientRect.height,
position: 'absolute',
}}
>
Autocomplete
$3
useTextSelection takes one argument called, which would be a dom element which constrains updates to inside the dom element.
Retrieve a reference to this dom element with the querySelector api or with React refs (recommended).
Here's an example:
`tsx
const MyTextSelectionComponent = () => {
const [ref, setRef] = useRef()
const { clientRect, isCollapsed } = useTextSelection(ref.current)
if (clientRect == null) return null
return (
<>
setRef(el)}>
style={{
left: clientRect.x,
top: clientRect.y + clientRect.height,
position: 'absolute',
}}
>
Autocomplete
$3
You can access the closest, common ancestor to all elements within the selection with the closestAncestor return value. This is forwarded directly from the commonAncestorContainer from the text range.
`tsx
const { clientRect, isCollapsed, commonAncestor } = useTextSelection(ref.current);
``