Highlight ranges

Mark text ranges in the open document with useHighlights, and keep them current as the document changes.

Call useHighlights(name, source, options) to mark text as a named set while a component is mounted. Highlights are local view state. They do not change the document and are not saved.

Highlight matching text

The following component marks each whole-word match of a list of terms. Style the glossary-term class with your own CSS, or omit className for the default fill.

import { useCallback } from 'react';
import { useHighlights, type Editor } from '@docx-editor.dev/react';

export function GlossaryMarks({ terms }: { terms: readonly string[] }) {
  // A stable function source, so the set refreshes only when `terms` changes.
  const findTerms = useCallback(
    (editor: Editor) => editor.findMatches(terms, { wholeWord: true }).flat(),
    [terms]
  );
  const { applied } = useHighlights('glossary', findTerms, { className: 'glossary-term' });
  return <span>{applied} marked</span>;
}

A function source runs again after each document change, so the marks follow the text. The set is removed when the component unmounts.

Configure a highlight set

Argument or fieldDescription
nameThe set name. Two sets with the same name replace each other's ranges.
sourceThe ranges, or a function of the editor that returns them.
options.classNameCSS classes added to every mark of the set.
options.activeIndexThe range to show in the active color, such as the current result of your own search list.
appliedThe number of ranges that resolve and paint.

Use highlights outside components

Call watchHighlights(editor, name, source, options) from @docx-editor.dev/core/editor to follow document changes. Call stop() on the returned watch to remove the set and stop watching. For a fixed set that does not refresh, call editor.setHighlights.

See also