Live Demo
TextareaInput
Usage
import { useTextSelection } from 'use-text-selection';
function MyComponent() {
const selection = useTextSelection({
onSelectionChange: (newSelection) => {
console.log('Selection changed:', newSelection);
}
});
return (
<div className="relative w-full min-h-[200px]">
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
className="w-full h-full min-h-[200px] p-4"
placeholder="Try selecting some text..."
/>
{selection.isSelected && selection.position && (
<div
style={{
top: selection.position.top,
left: selection.position.left
}}
>
Your tooltip content
</div>
)}
</div>
);
}API Reference
Options
onSelectionChange?: (selection: TextSelection) => void- Callback fired when selection changesoffsetLeft?: number- Horizontal offset for tooltip positioning (default: 2)offsetTop?: number- Vertical offset for tooltip positioning (default: 8)
Return Value
selectedText: string | null- The currently selected textposition: Position | null- Coordinates for positioning the tooltipisSelected: boolean- Whether text is currently selectedelement: HTMLElement | null- The element containing the selection