useSelection
Returns what the user has selected: the paragraph being edited, or the ids of the selected blocks. Re-renders the component when the selection changes.
const selection = useSelection() // Selection | undefinedThe value is a Selection:
| Value | Meaning |
|---|---|
{ type: 'text', blockId } | A paragraph is in text editing: the caret or a text range is inside the paragraph blockId. |
{ type: 'blocks', blockIds } | Whole blocks are selected: paragraphs, annotations, or widgets. |
undefined | Nothing is selected, or no document is loaded. |
Behavior
- Only the selection type and the ids are tracked. Moving the caret or changing the text range within the same paragraph, and editing a selected block, don't re-render the component; read the block content with useSelectedBlocks instead.
- Deleted blocks are left out of
blockIds. When none of the selected blocks exists, the value isundefined; if an undo restores them, they come back selected. - The ids are session-scoped: don't store them across page reloads.
Example
import { useSelection } from '@sdk-pdf/react'
function SelectionToolbar() {
const selection = useSelection()
if (!selection) return null
return (
<div role="toolbar">
{selection.type === 'text'
? 'Editing text'
: `${selection.blockIds.length} selected`}
</div>
)
}To change the selection, see useSelectBlocks. To read it inside an event handler without subscribing, see useSelectedBlocksGetter.