Skip to content

useSearchContext

The useSearchContext hook provides access to the search state and functions for searching through a PDF document.

It enables you to create custom search controls and access search results within the PDF document.

This is useful when building custom search interfaces or displaying search-related information.

Return Type

NameTypeDescription
searchstringThe current search query string
setSearchDispatch<SetStateAction<string>>Update the search query string.
This triggers a new search with the provided query
loadingbooleanIndicate whether the search is in progress
matchesMatchValue[]An array containing all the search matches found in the document.
Each match contains information about its position and content
totalMatchesnumberThe total number of matches found in the document
currentMatchPositionnumberThe index of the currently selected search match (1-based).
For example, if there are 5 total matches and the second match is selected, this value would be 2
currentMatchMatchValue | nullThe current match
nextMatch() => voidNavigate to the next match
prevMatch() => voidNavigate to the previous match
searchOptionsSearchOptionsThe search options
setSearchOptionsDispatch<SetStateAction<SearchOptions>>Update the search options
currentMatchElementHTMLElement | nullThe current match element
setCurrentMatchElementDispatch<SetStateAction<HTMLElement | null>>Update the current match element

Usage

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

This example shows how to create a CustomSearch component which uses useSearchContext hook to handle the search functionality.

import { useState, useCallback } from 'react'
import { RPConfig, RPProvider, RPDefaultLayout, RPPages, useSearchContext } from '@pdf-viewer/react'
const CustomSearch = () => {
const { search, setSearch, currentMatchPosition, totalMatches, nextMatch, prevMatch, loading } = useSearchContext()
const [searchValue, setSearchValue] = useState(search)
const handleChange = useCallback((e) => {
setSearchValue(e.target.value)
}, [])
const handleSubmit = useCallback(() => {
setSearch(searchValue)
}, [searchValue, setSearch])
const handleNext = useCallback(() => {
nextMatch()
}, [nextMatch])
const handlePrev = useCallback(() => {
prevMatch()
}, [prevMatch])
return (
<div>
<input value={searchValue} onChange={handleChange} />
<button onClick={handleSubmit}>Submit</button>
<span>
{currentMatchPosition} / {totalMatches}
</span>
<button onClick={handlePrev}>Prev</button>
<button onClick={handleNext}>Next</button>
{loading && <div>searching...</div>}
</div>
)
}
export const AppPdfViewer = () => {
return (
<RPConfig>
<RPProvider src="https://cdn.codewithmosh.com/image/upload/v1721763853/guides/web-roadmap.pdf">
<CustomSearch />
<RPDefaultLayout>
<RPPages />
</RPDefaultLayout>
</RPProvider>
</RPConfig>
)
}