Preview a document inside a modal

In this example, we will see how to preview a PDF document in a full screen modal.

Create a modal

It's easy to create a modal with React. First of all, we need a flag to track if the modal is opened or not:
import { useState } from 'react';
const [shown, setShown] = useState(false);
The modal usually can be opened by triggering the click event of a button. The event handler simply calls setShown(true):
<button onClick={() => setShown(true)}>Open modal</button>
The modal then is attached to the body element:
const modalBody = () => (
// Build the modal body
// ...
);
return (
<>
<button onClick={() => setShown(true)}>Open modal</button>
{shown && ReactDOM.createPortal(modalBody(), document.body)}
</>
);
In order to make the modal take full screen size, we need to add some CSS styles to the modal:
const modalBody = () => (
<div
style={{
backgroundColor: '#fff',
/* Fixed position */
left: 0,
position: 'fixed',
top: 0,
/* Take full size */
height: '100%',
width: '100%',
/* Displayed on top of other elements */
zIndex: 9999,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
}}
>
<!-- We will display viewer here -->
<Viewer fileUrl="/path/to/document.pdf" />
</div>
);