In this example, we will use another functions to highlight given keywords and navigate between matches. The search plugin instance provides the following functions:
| Method | Description | From |
|---|
`clearHighlights` | Clear the highlights | 2.4.0 |
`highlight` | Highlight multiple keywords | 2.4.0 |
`jumpToNextMatch` | Jump to the next match | 2.4.0 |
`jumpToPreviousMatch` | Jump to the previous match | 2.4.0 |
The `highlight` function accepts a single or an array of keywords. Each keyword can be a `string`, `RegExp` or `FlagKeyword`.
The `FlagKeyword` type determines if we want to match the case or find the whole word:
interface FlagKeyword {
keyword: string;
matchCase?: boolean;
wholeWords?: boolean;
}
The following sample code highlights the `document` and `PDF` words, but the results have to match the case of `PDF`. So the `PDF` words are highlighted, but `pdf` words are not.
import { searchPlugin } from '@react-pdf-viewer/search';
const searchPluginInstance = searchPlugin();
const { highlight } = searchPluginInstance;
highlight([
'document',
{
keyword: 'PDF',
matchCase: true,
},
]);
We can build the controls to turn on or off the `matchCase` and `wholeWords` properties.
In combination with the `highlight`, `jumpToNextMatch` and `jumpToPreviousMatch` methods, we can create a custom search control as following:
See also