Track text selection with positioning for tooltips
Tracks text selection within a container or the entire document. Returns the selected text and its bounding rectangle for positioning tooltips or popovers.
Installation
npm install betteruse
Usage
import { useSelection } from 'betteruse'import { useRef } from 'react'function TextWithPopover() { const containerRef = useRef<HTMLDivElement>(null) const { text, rect, isSelected, clear } = useSelection(containerRef) return ( <div ref={containerRef}> <p>Select some text in this paragraph to see a popover appear.</p> {isSelected && rect && ( <div style={{ position: 'fixed', top: rect.top - 40, left: rect.left + rect.width / 2, transform: 'translateX(-50%)', }} > <button onClick={() => navigator.clipboard.writeText(text)}> Copy "{text.slice(0, 20)}..." </button> </div> )} </div> )}
API Reference
useSelection(containerRef?)
Prop
Type
Default
Description
containerRef
RefObject<HTMLElement>
-
Optional ref to scope selection to a specific element
Return Value
Prop
Type
Default
Description
text
string
-
The selected text
rect
SelectionRect | null
-
Bounding rectangle of the selection
isSelected
boolean
-
Whether text is currently selected
clear
() => void
-
Clear the current selection
SelectionRect
Prop
Type
Default
Description
x
number
-
X coordinate
y
number
-
Y coordinate
width
number
-
Width of selection
height
number
-
Height of selection
top
number
-
Top position
left
number
-
Left position
right
number
-
Right position
bottom
number
-
Bottom position
How It Works
Listens to the selectionchange event on the document
Debounces updates (100ms) for performance
If a containerRef is provided, validates selection is within that element
Returns the selected text and its bounding rectangle
This hook is SSR-safe. Selection tracking only happens on the client.