Skip to content

useZoomContext

The useZoomContext hook provides access to the scale state and functions for scaling the currently loaded PDF file within React PDF.

It enables you to create custom scale controls or other UI elements that can trigger the scaling of the PDF file.

Return Type

NameTypeDescription
currentZoomnumberNormalize scale level of the current PDF page to use with pdf.js scale
setZoomLevelReact.Dispatch<React.SetStateAction<number>>Update the scale level of the current PDF page
zoomLevelnumberAccess the current scale level of the current PDF page

Usage

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

This example shows how to create a CustomZoomLayout component which uses useZoomContext to access the PDF page’s scale

import { useCallback } from 'react'
import {
RPConfig,
RPProvider,
RPDefaultLayout,
RPPages,
useZoomContext
} from '@pdf-viewer/react'
const CustomZoomLayout = () => {
// Consume from the controller provider
const { zoomLevel, setZoomLevel } = useZoomContext()
// zoom in 10 and max 1000
const handleZoomIn = useCallback(() => {
setZoomLevel((prev) => Math.min(prev + 10, 1000))
}, [setZoomLevel])
// zoom out 10 and min 10 to prevent scale to be less than 1
const handleZoomOut = useCallback(() => {
setZoomLevel((prev) => Math.max(prev - 10, 10))
}, [setZoomLevel])
return (
<div>
{zoomLevel}
<button onClick={handleZoomIn}>zoom in</button>
<button onClick={handleZoomOut}>zoom out</button>
</div>
)
}
export const AppPdfViewer = () => {
return (
<RPConfig licenseKey={YOUR_LICENSE_KEY}>
<RPProvider src="https://cdn.codewithmosh.com/image/upload/v1721763853/guides/web-roadmap.pdf">
<CustomZoomLayout />
<RPDefaultLayout>
<RPPages />
</RPDefaultLayout>
</RPProvider>
</RPConfig>
)
}