Skip to content

useSelection

This hook returns the current selected text on the window or a specific element, and other things.

Parameters

  • the ref object of the target element (default is document).

WARNING

Do not use window as the target element, it will only work with HTML elements.

Return Values

NameTypeDescription
refRefObjectthe target element reference.
textStringthe selection text or null.
rectObjectthe selection rectangle (top, left, width...).
isCollapsedBooleanindicates whether or not there is currently any text selected.

Example Usage

tsx
import { useSelection } from 'react-pre-hooks';

export default function Example() {
  const { text, rect, isSelecting } = useSelection();

  return (
    <main>
      {!isSelecting && text && (
        <span style={{ top: rect.top + 'px', left: rect.left + rect.width / 2 }}>
          Quote this!
        </span>
      )}
      <article>
        <h1>Select anything.</h1>
        <p>
          A user may make a selection from left to right (in document order)
          or right to left (reverse of document order). The anchor is where
          the user began the selection and the focus is where the user ends 
          the selection. If you make a selection with a desktop mouse,
          the anchor is placed where you pressed the mouse button, and 
          the focus is placed where you released the mouse button.
        </p>
      </article>
    </main>
  );
}
import { useSelection } from 'react-pre-hooks';

export default function Example() {
  const { text, rect, isSelecting } = useSelection();

  return (
    <main>
      {!isSelecting && text && (
        <span style={{ top: rect.top + 'px', left: rect.left + rect.width / 2 }}>
          Quote this!
        </span>
      )}
      <article>
        <h1>Select anything.</h1>
        <p>
          A user may make a selection from left to right (in document order)
          or right to left (reverse of document order). The anchor is where
          the user began the selection and the focus is where the user ends 
          the selection. If you make a selection with a desktop mouse,
          the anchor is placed where you pressed the mouse button, and 
          the focus is placed where you released the mouse button.
        </p>
      </article>
    </main>
  );
}

Released under the MIT License.