Back to Hooks

useTextSelection

useTextSelection.tsx

useTextSelection

INTERACTION

// Detect and return currently selected text by user

Quick Usage

const { text, isSelected, clearSelection } = useTextSelection();

Features

Selection Detection
Range Information
Bounding Rect
Programmatic Control

When to Use

Perfect for text annotation tools, highlighting features, selection-based actions, or any text interaction functionality.

Interactive Example

Select any text in this paragraph to see the text selection hook in action. This is a longer paragraph with multiple sentences to demonstrate text selection capabilities. You can select individual words, sentences, or the entire paragraph.

Select some text above to see selection information

Complete Example

import { useTextSelection } from '@usegrand/react-hokss';

function TextAnnotator() {
  const { text, isSelected, range, rect, clearSelection, selectText } = useTextSelection();

  const handleHighlight = () => {
    if (isSelected && text) {
      // Create annotation or highlight
      console.log('Highlighting:', text);
    }
  };

  return (
    <div>
      <p ref={textRef}>
        This is some text that can be selected for annotation.
      </p>
      {isSelected && (
        <div>
          <p>Selected: "{text}"</p>
          <button onClick={handleHighlight}>Highlight</button>
          <button onClick={clearSelection}>Clear</button>
        </div>
      )}
    </div>
  );
}

API Reference

Parameters

Returns

TextSelectionResult

Object containing selection state and control functions

text

Currently selected text string

range

Selection range with start and end positions

isSelected

Boolean indicating if text is currently selected

rect

Bounding rectangle of the selection

clearSelection

Function to clear the current selection

selectText

Function to programmatically select text