Skip to content

Making React PDF Reusable

React on Client

1. Create a reusable component

ReactPdfViewer.jsx
import { RPProvider, RPConfig, RPDefaultLayout, RPPages } from '@pdf-viewer/react'
export const ReactPdfViewer = () => {
return (
<RPProvider
{...props}
src="https://cdn.codewithmosh.com/image/upload/v1721763853/guides/web-roadmap.pdf"
>
<RPDefaultLayout>
<RPPages />
</RPDefaultLayout>
</RPProvider>
)
}

2. Use ReactPdfViewer component anywhere within the RPConfig part

App.jsx
import { RPConfig } from '@pdf-viewer/react'
import { ReactPdfViewer } from './ReactPdfViewer'
export const App = () => {
return (
// Place `RPConfig` within a parent component to use `ReactPdfViewer`
<RPConfig
licenseKey="YOUR_LICENSE_KEY"
// ...Other configs
>
{/* ...Other components */}
<div style={{ height: '660px' }}>
<ReactPdfViewer />
</div>
{/* ...Other components */}
</RPConfig>
)
}

Next.js

1. Prepare a reusable component and a config componet

Reusable Component

Import four parts (RPProvider, RPDefaultLayout, RPPages, RPConfig) and group them into a single component

ReactPdfViewer.jsx
'use client'
import { RPProvider, RPConfig, RPDefaultLayout, RPPages } from '@pdf-viewer/react'
export const ReactPdfViewer = () => {
return (
<RPProvider
{...props}
src="https://cdn.codewithmosh.com/image/upload/v1721763853/guides/web-roadmap.pdf"
>
<RPDefaultLayout>
<RPPages />
</RPDefaultLayout>
</RPProvider>
)
}
Config component

This component is used to create a global config for all instances of the resuable component

ReactPdfViewerConfig.jsx
import { RPConfig } from '@pdf-viewer/react'
export const ReactPdfViewerConfig = ({ children }) => {
return (
<RPConfig
licenseKey="YOUR_LICENSE_KEY"
// ...Other config
>
{children}
</RPConfig>
)
}

2. Use dynamic import with ssr:false option to prevent server side rendering

pdfjs has to be run on the client side so the React PDF component should not run on server side.

Reusable component
LazyReactPdfViewer.jsx
import dynamic from 'next/dynamic'
export const LazyReactPdfViewer = dynamic(() => import('./ReactPdfViewer'), { ssr: false })
Config component
LazyReactPdfViewerConfig.jsx
import dynamic from 'next/dynamic'
export const LazyReactPdfViewerConfig = dynamic(() => import('./ReactPdfViewerConfig'), {
ssr: false
})

3. Place the config component in your Next project

Place LazyReactPdfViewerConfig component in Page or Layout to provide global config to LazyReactPdfViewer

layout.jsx
import { LazyReactPdfViewerConfig } from './LazyReactPdfViewerConfig'
export default function Layout({ children }) {
// Place `RPConfig` within a parent component to use `ReactPdfViewer`
return <LazyReactPdfViewerConfig>{children}</LazyReactPdfViewerConfig>
}

4. Start using your reusable component

Use LazyReactPdfViewer component anywhere in your Page

Page.jsx
import { LazyReactPdfViewer } from './LazyReactPdfViewer'
export default function Page() {
return (
<div style={{ height: '660px' }}>
<LazyReactPdfViewer />
</div>
)
}