Skip to content

useHighlightContext

The useHighlightContext hook grants access to the state and functions for managing highlighted keywords.

It enables highlighting multiple keywords in different colors within a PDF viewer while providing convenient state management and control functions.

Return Type

NameTypeDescription
highlight(value: TextHighlight[]) => Promise<void>Highlight specified keyword(s) (as strings or regular expression patterns) in the PDF document with customizable options
highlightKeywordsTextHighlight[]Provide the highlight keywords information eg. keyword, highlight color, options
highlightMatchesMatchHighlight[]Provide the highlight matches information eg. page number, highlighted texts position
clear() => voidRemoves all existing highlights from the PDF document

Usage

To ensure the highlight context can be accessed, you will need to use useHighlightContext inside a component which is a child of RPProvider.

This example shows how to create a HighlightWords component that utilizes useHighlightContext hook to manage the state and functions for highlighting words.

NOTE: Ensure that the highlightColor value includes opacity so the highlighted text remains visible.

import {
RPConfig,
RPProvider,
RPDefaultLayout,
RPPages,
useHighlightContext
} from '@pdf-viewer/react'
import { useEffect } from 'react'
const HighlightWords = () => {
const { highlight } = useHighlightContext()
useEffect(() => {
highlight([
{
keyword: 'WEB',
highlightColor: 'rgba(0, 255, 0, 0.5)',
options: { matchCase: true, wholeWords: true }
},
{
// This regular expression matches the word "roadmap" in a case-insensitive manner
keyword: /roadmap/gi,
highlightColor: 'rgba(255, 0, 255, 0.5)'
}
])
}, [])
return <>{/* You can add UI elements here */}</>
}
export const AppPdfViewer = () => {
return (
<RPConfig licenseKey={YOUR_LICENSE_KEY}>
<RPProvider src="https://cdn.codewithmosh.com/image/upload/v1721763853/guides/web-roadmap.pdf">
<HighlightWords />
<RPDefaultLayout>
<RPPages />
</RPDefaultLayout>
</RPProvider>
</RPConfig>
)
}