useSelectedBlocks

Returns the currently selected blocks as snapshots and re-renders the component when the selection, or a selected block itself, changes.

const selectedBlocks = useSelectedBlocks() // readonly Block[]
  • The entries are Block snapshots: plain objects describing each block at the moment of reading. A snapshot doesn't update with the document, and changing it doesn't change the document; apply changes through the command hooks, such as useSetWidgetProps.
  • The array reference changes whenever the content changes, so useEffect on it handles selection changes imperatively.
  • When only the selection itself matters, not the block content, useSelection re-renders less often. To read the selected blocks inside an event handler, use useSelectedBlocksGetter.

Block kinds

Block is a union told apart by type and subtype. Every block carries a session-scoped id and its pageId.

KindDiscriminatorFields
Widgettype: 'annotation', subtype: 'Widget'widgetType and the widget properties listed in useSetWidgetProps.
InkAnnotationtype: 'annotation', subtype: 'Ink'The ink properties listed in useInkAnnotationCreate.
StampAnnotationtype: 'annotation', subtype: 'Stamp'The box and imageId, described in useStampAnnotationCreate.
UnknownBlocktype: 'unknown'Only id and pageId. Paragraphs and the annotation kinds without a dedicated snapshot type yet, such as shapes and lines.

Example

import { useSelectedBlocks } from '@sdk-pdf/react'

function SelectionSummary() {
  const selectedBlocks = useSelectedBlocks()

  if (selectedBlocks.length === 0) return null

  const widgetCount = selectedBlocks.filter(
    (block) => block.type === 'annotation' && block.subtype === 'Widget'
  ).length

  return (
    <span>
      {selectedBlocks.length} selected, {widgetCount} form fields
    </span>
  )
}

On this page