useTextSelection

A React hook for creating elegant text selection interactions in textareas and input fields, similar to Medium's selection experience.

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 changes
  • offsetLeft?: 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 text
  • position: Position | null - Coordinates for positioning the tooltip
  • isSelected: boolean - Whether text is currently selected
  • element: HTMLElement | null - The element containing the selection