Home > front end >  View pdf file in react app throwing error
View pdf file in react app throwing error

Time:12-22

I'm trying to open pdf file in react app on menu click but getting this error

You may need an appropriate loader to handle this file type, 
currently no loaders are configured to process this file

I have static pdf file in my project directory, I would like just open it in a new tab in menu click event.

The pdf file itself is not really large about 7mb

What is the best way to do it ?

import testPDF from "../assets/pdf/test.pdf";

  const handleOpenPDF = () => {
    window.open(testPDF);
  }

  <Menu.Item onClick={handleOpenPDF}>
    <Text>
      View PDF
    </Text>
  </Menu.Item>

CodePudding user response:

You could use the https://react-pdf.org/ library. Should be able to install it, import it, then include it in your code like so:

import { Document } from 'react-pdf';

const handleOpenPDF = () => {
  const container = document.createElement('div');
  ReactDOM.render(
    <Document
      file={testPDF}
      onl oadSuccess={() => console.log('PDF successfully loaded!')}
    >
      <p>Loading PDF...</p>
    </Document>,
    container
  );
  window.open().document.write(container.innerHTML);
};

Hope this helps! React-pdf is a great, user-friendly library.

CodePudding user response:

The error is caused by the fact you are importing the PDF file like it was a JS module. You should serve your pdf as a static file on your server instead and use a the static file URL to display/download it.

  • Related