Skip to content

useTextSelection

Tracks current text selection and bounding box.

Tracks current text selection and bounding box.

Import

import { useTextSelection } from '@kamod-ch/hooks'

Live demo

Basic demo

Tracks current text selection and bounding box.

Browser-only demo

This demo starts after the page mounts in the browser.
import { useRef } from 'preact/hooks'
import { useTextSelection } from '@kamod-ch/hooks'

export default function UseTextSelectionDemo() {
  const ref = useRef<HTMLDivElement>(null)
  const selection = useTextSelection(ref)

  return (
    <div>
      <div ref={ref} class="demo-target-box">Select some text inside this paragraph to inspect the current selection.</div>
      <p><strong>Selected text:</strong> {selection.text || 'none'}</p>
    </div>
  )
}

API

TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
interface Rect {
    top: number;
    left: number;
    bottom: number;
    right: number;
    height: number;
    width: number;
}
export interface State extends Rect {
    text: string;
}
declare function useTextSelection(target?: BasicTarget<Document | Element>): State;
export default useTextSelection;
/

SSR considerations

This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.

Browser compatibility

Requires the corresponding browser API to exist in the current environment.