My goal is to have a user upload a PDF file and preview it using React-PDF. I am using Mantine’s Dropzone for file upload and loading the file into preview using React-pdf.
The issue is that I am failing to load the pdf file and getting error
Error: Setting up fake worker failed: "Cannot load script at: http://localhost:5173/pdf.worker.js".
My code:
import { useState, useRef, useEffect } from 'react';
import { Document, Page } from 'react-pdf';
import { Button, Group } from '@mantine/core';
import { Dropzone, PDF_MIME_TYPE } from '@mantine/dropzone';
type PDFFile = string | File | null;
const FileDropzone = () => {
const dropzoneOpenRef = useRef<() => void>(null);
const [file, setFile] = useState<PDFFile>(null);
const onFileChange = (files: File[]) => {
if (files && files[0]) {
setFile(files[0]);
}
};
useEffect(() => {
console.log(file);
}, [file]);
return (
<>
<h1>React Drop File</h1>
<p>Click on the Vite and React logos to learn more</p>
<Dropzone
openRef={dropzoneOpenRef}
onDrop={onFileChange}
onReject={(file) => console.log('Rejected files', file)}
maxSize={5 * 1024 ** 2}
accept={PDF_MIME_TYPE}>
<Group justify='center' mt='md'>
<Button onClick={() => dropzoneOpenRef.current?.()}>
Select Files
</Button>
</Group>
</Dropzone>
<div>
<Document file={file} onLoadError={console.error}>
<Page pageNumber={1} />
</Document>
</div>
</>
);
};
export default FileDropzone;