Display the thumbnail of a given page

Let's imagine that we have a page that shows the list of documents. Each document can be represented by a thumbnail. Clicking the thumbnail will bring users to the details page that displays the full document for example.
This example will show you how to do it with a custom plugin.

Create a custom plugin

As we know, the viewer is constructed by multiple plugins. When the viewer renders the document's pages, it executes the `renderViewer` functions provided by all registered plugins.
We will create a plugin named `pageThumbnailPlugin` to reset the output of different plugins:
import type { Plugin, RenderViewer } from '@react-pdf-viewer/core';
export interface PageThumbnailPluginProps {
PageThumbnail: React.ReactElement;
}
export const pageThumbnailPlugin = (props: PageThumbnailPluginProps): Plugin => {
const { PageThumbnail } = props;
return {
renderViewer: (renderProps: RenderViewer) => {
let { slot } = renderProps;
slot.children = PageThumbnail;
// Reset the sub slot
slot.subSlot.attrs = {};
slot.subSlot.children = <></>;
return slot;
},
};
};
The plugin removes the rendered parts of other plugins and displays the thumbnail of a particular page which can be passed to the `PageThumbnail` property.

The Cover component

We can use the `Cover` component provided by the Thumbnail plugin and pass it to the `pageThumbnailPlugin` plugin:
import { pageThumbnailPlugin } from './pageThumbnailPlugin';
const thumbnailPluginInstance = thumbnailPlugin();
const { Cover } = thumbnailPluginInstance;
const pageThumbnailPluginInstance = pageThumbnailPlugin({
PageThumbnail: <Cover getPageIndex={() => 0} />,
});
It has two properties:
(? denotes an optional property)
PropertyTypeDescriptionFrom
`getPageIndex`?`Function`Determine the page index2.9.0
`width`?`number`The width of cover (in pixels)3.12.0
The `getPageIndex` property of the `Cover` component is a function whose signature is
getPageIndex = ({ numPages: number }) => number;
The `numPages` is the total number of pages of the current document. Here are some examples of using the `Cover` component to display the thumbnails of different pages:
// Display the thumbnail of the first page
<Cover getPageIndex={() => 0} />
// Display the thumbnail of the second page
<Cover getPageIndex={() => 1} />
// Display the thumbnail of the last page
<Cover getPageIndex={props => props.numPages - 1} />
Finally, we need to register the plugin instances created above with the `Viewer` component:
<Viewer plugins={[pageThumbnailPluginInstance, thumbnailPluginInstance]} />
The following demonstration displays the thumbnail of the first page. In reality, it's possible to pick a dynamic page. For example, it can be the page users opened the last time.

See also