A React hook for creating elegant text selection interactions in textareas and input fields, similar to Medium's selection experience.
- 🎯 Accurate tooltip positioning
- 🖱️ Smooth selection tracking
- 📱 Responsive and adaptive
- 🎨 Customizable offsets and styling
- 📦 Zero dependencies
- 💪 TypeScript support
import { useTextSelection } from 'use-text-selection';
function MyComponent() {
const selection = useTextSelection({
offsetLeft: 2, // Optional: Adjust horizontal offset
offsetTop: 8, // Optional: Adjust vertical offset
});
return (
<div className="relative w-full min-h-[200px]">
<textarea
value={text}
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>
);
}
onSelectionChange?: (selection: TextSelection) => void
- Callback when selection changesoffsetLeft?: number
- Horizontal offset for the tooltip (default: 2)offsetTop?: number
- Vertical offset for the tooltip (default: 8)
selectedText: string | null
- Currently selected textposition: Position | null
- Coordinates for tooltip positioningisSelected: boolean
- Whether text is currently selectedelement: HTMLElement | null
- Element containing the selection
MIT