Jump to the first match of pre-defined keywords automatically

As mentioned in the Highlight keywords programmatically example, we can use the `highlight` function provided by an instance of the search plugin to highlight given keywords. The snippet below performs searching and highlighting for two keywords, `document`, and `PDF`. The matches for the second keyword have to match the case exactly.
import { searchPlugin } from '@react-pdf-viewer/search';
const searchPluginInstance = searchPlugin();
const { highlight } = searchPluginInstance;
// Highlight keywords
highlight([
'document',
{
keyword: 'PDF',
matchCase: true,
},
]);
The function will search for matches across the document pages, and highlight the matches on corresponding pages when you scroll down. If you want to jump to the first match automatically, then you need to invoke the function when the document is loaded.
The `Viewer` component provides the `onDocumentLoad` event for that purpose:
const [isDocumentLoaded, setDocumentLoaded] = React.useState(false);
const handleDocumentLoad = () => setDocumentLoaded(true);
<Viewer onDocumentLoad={handleDocumentLoad} />;
Here we use a simple state named `isDocumentLoaded` to check whether a document is loaded successfully. Depending on its value, the highlight function will be invoked:
React.useEffect(() => {
if (isDocumentLoaded) {
highlight({
keyword: 'Administration',
matchCase: true,
});
}
}, [isDocumentLoaded]);

See also