How to integrate React-PDF in ReactJS ?
React-PDF is a package that helps users to display PDF files in their React app. By using react-pdf package we can add PDF files in our React app as if they were images. To use the latest version of react-pdf package, our project should use React 16.3 or later. We can integrate react-pdf using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app my-app
Step 2: After creating your project folder(i.e. my-app), move to it by using the following command.
- Step 3: After creating the React application, Install the react-pdf package using the following command.
npm install react-pdf
Step 4: Add sample.pdf file to my-app/src folder which you want to display.
Project Structure :
Example: Add the following code in the App.js file. Here, App is our default component where we have written our code.
Note: Instead of importing/requiring react-pdf directly, we had used entry points which are being provided by react-pdf because entry points enable PDF.js worker which is crucial for performance. This makes sure that PDF files will be rendered in a different thread without affecting the performance of the page.
Step to Run Application: Run the application using the following command from the root directory of the project.
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.