To implement a PDF preview component using React without an iframe, we'll use the react-pdf library. Here's the updated component:
import React from "react";
import PropTypes from "prop-types";
import styles from "../styles/PdfPreview.module.css";
import { Viewer } from '@react-pdf-viewer/core';
import { defaultLayoutPlugin } from '@react-pdf-viewer/default-layout';
import '@react-pdf-viewer/core/lib/styles/index.css';
import '@react-pdf-viewer/default-layout/lib/styles/index.css';
export default function PdfPreview({ pdfUrl }) {
const defaultLayoutPluginInstance = defaultLayoutPlugin();
return (
<div className={styles.pdfPreview}>
<Viewer
file={pdfUrl}
plugins={[defaultLayoutPluginInstance]}
/>
</div>
);
}
PdfPreview.propTypes = {
pdfUrl: PropTypes.string.isRequired,
};
Key changes made:
- Replaced
iframe with react-pdf's Viewer component
- Added required plugins for document display and layout
- Imported necessary CSS files for proper styling
- Maintained the original styling className wrapper
You'll need to install the required packages:
npm install @react-pdf-viewer/core @react-pdf-viewer/default-layout
This implementation provides:
- Better React integration
- PDF rendering controls (zoom, page navigation)
- Responsive layout
- Maintained styling through CSS modules
- Accessibility improvements over iframe
Note: Ensure your PDF files are served with proper CORS headers if loading from external sources.