React PDF viewer
v1.6.0

Example: Customize error renderer

From v1.6.0, you can use a custom error renderer if the viewer can't load the document by using the renderError option. It is a function that takes a LoadError parameter and returns an element.

The LoadError type consists of two properties:

  • message which indicates the error message
  • name which indicates the name of exception

The name property can take one of the values below:

  • AbortException
  • FormatError
  • InvalidPDFException
  • MissingPDFException
  • PasswordException
  • UnexpectedResponseException
  • UnknownErrorException

By relying on the name property, you can customize the error message as well.

import Viewer, { LoadError } from '@phuocng/react-pdf-viewer';

const renderError = (error: LoadError) => {
    let message = '';
    switch (error.name) {
        case 'InvalidPDFException':
            message = 'The document is invalid or corrupted';
            break;
        case 'MissingPDFException':
            message = 'The document is missing';
            break;
        case 'UnexpectedResponseException':
            message = 'Unexpected server response';
            break;
        default:
            message = 'Cannot load the document';
            break;
    }

    return (
        <div
            style={{
                alignItems: 'center',
                display: 'flex',
                height: '100%',
                justifyContent: 'center'
            }}
        >
            <div
                style={{
                    backgroundColor: '#e53e3e',
                    borderRadius: '0.25rem',
                    color: '#fff',
                    padding: '0.5rem',
                }}
            >
                {message}
            </div>
        </div>
    );
};

<Viewer
    fileUrl={fileUrl}
    renderError={renderError}
/>

(The sample code)

Cannot load the document