I keep encountering an error every time I attempt to utilize react-pdf within my Next.js 14.2 project. What could be causing this

Struggling with a react-pdf issue in my next js project despite following various tutorials.

The error message I receive is:

  ⨯ Instead change the require of react-pdf.js in C:\Users\TCET ADMIN\Desktop\next\.next\server\app\(client)\page.js to a dynamic
 import() which is available in all CommonJS modules.
     at @react-pdf/renderer (C:\Users\TCET ADMIN\Desktop\next\.next\server\app\(client)\page.js:110:18)
     ... more errors listed here ...

https://i.sstatic.net/WikcImRw.png

Despite trying multiple tutorials, my approach involved creating custom components and passing different props to them. Below are snippets from my code:

MainComponent.tsx

   <DownloadButton
       disabledButton={!confirmAgreement}
       onClick={form.handleSubmit(onSubmit)}
       isPending={isPending}
       form={form} />
     </DialogClose>

DownloadButton.tsx

'use client'
import React from 'react'
... more code snippet continued here ...

And then this my CreateAppointmendPDF.tsx file where I encounter issues using features from @react-pdf/renderer.

import { Document, Font, Page, Text, View } from '@react-pdf/renderer'

const CreateDocumentPDF = ({
    form
}: any) => {
    return (
        <Document>
        ... content here ...
        </Document>
    )
}

export default CreateDocumentPDF

Answer №1

It seems like version 4.0.0 of @react-pdf/renderer has completely dropped support for CommonJS modules, which is disappointing.

To resolve this issue, you can either revert back to version 3.4.5 of @react-pdf/renderer or update your TypeScript compiler settings to output esmodules.

For example, you can modify your tsconfig.json file with the following configuration:

{
  "compilerOptions": {
    "module": "es6" // or "esnext", "es2020", "es2022", etc.
  }
}

Refer here for more information on the "module" TS option.

I faced the same problem and encountered additional issues when changing my output settings. As a result, I decided to downgrade to version 3.4.5. Hopefully, future versions will reintroduce cjs exports.

UPDATE:

Unfortunately, the decision to remove CommonJS support is final, as mentioned by the authors:
https://github.com/diegomura/react-pdf/issues/2907

Answer №2

To enhance the functionality of your application, make sure to update your next.config.js file with the following changes:

const updatedConfig = {
      experimental: {
      serverComponentsExternalPackages: ['@react-pdf/renderer'],
    }
 };

For additional details and insights, refer to the documentation available at NextJS Docs as well as the information provided by React-pdf Docs.

Answer №3

To incorporate a PDF download link into your project, you can easily import PDFDownloadLink from the @react-pdf/renderer module using the following syntax:

import { PDFDownloadLink, PDFViewer } from "@react-pdf/renderer";

Given that Next.js utilizes Server-Side Rendering (SSR) and @react-pdf/renderer is geared towards the browser environment, it is advisable to employ a dynamic import with ssr: false when importing components dependent on @react-pdf/renderer :

In the DownloadButton.tsx component file, you can import PDFDownloadLink in the usual manner:

import { PDFDownloadLink } from "@react-pdf/renderer";

Subsequently, within your MainComponent.tsx where DownloadButton.tsx is utilized, you can implement a dynamic import like so:

import dynamic from 'next/dynamic';

const DownloadButton = dynamic(
  () => import('./DownloadButton'),
  { ssr: false }
);

export default function MainComponent() {
  return (
    <div>
      <DownloadButton />
    </div>
  );
}

This approach ensures that DownloadButton.tsx functions correctly on the client side in compliance with the requirements of @react-pdf/renderer components.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Blurring the boundary of Slick's carousel with a fade effect

Currently, I am utilizing the Slick Carousel plugin developed by Ken Wheeler. In the image provided below, you can observe that when a slide is transitioning at the edge, it appears to be abruptly cut off. I am contemplating the implementation of a "fading ...

Steps for choosing a row from a dynamic table when clicking the mouse

Is there a way to retrieve a row's value upon mouse click or by checking the checkbox in the provided HTML table? Below is the JavaScript code for fetching values from a table using Spry, sourced from an XML file: var ds1 = new Spry.Data.XMLDataSet( ...

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

Complete the form to receive the redirection link

For the purpose of registering a server on a website, I am required to input data. This involves filling out a form on the initial webpage and upon submission, being directed to a dynamically generated page where further information must be entered. It is ...

The React.js search feature consistently retrieves identical content every time

I am currently working on a project to create a search engine using React.js, specifically to search for GIPHY gifs through their API. However, I have encountered an issue where the gifs displayed do not update when I type in new words after erasing the pr ...

Transferring an array of interfaces between Angular 2 components

Encountering issues with passing an Array of data between components using @Input. Here is the code snippet: public ngOnInit() { this.applications = new Array<ApplicationEntryInterface>(); (...) let shortTermData = new ShortTermApplicationAdapte ...

Creating a new nested object in JavaScript using the keys of the current object

What is the most efficient method for creating a new object based on the keys of the current object? Each key in the original object should correspond to a specific element in the new object - for example, activityName1 should match the first element' ...

Using the -t or --testNamePattern in Jest will execute all tests

Currently, I have set up my testing framework using jest and ts-jest based on the guidelines provided by the ts-jest documentation. When I execute the command yarn test --listTests, I can identify the specific test file I intend to run: processNewUser.ts ...

Issues encountered with the v-model functionality in a Laravel and Vue.js integrated to-do list

Recently, I created a to-do list application using Laravel and Vue.js. The concept is simple: users can add categories and within each category, they can create a list of tasks or to-dos. However, I encountered a minor issue with the input fields - whateve ...

The .AppendChild() method does not appear to be working as expected following the completion of

Encountering a peculiar problem here. The scripts run smoothly, but the content doesn't display on screen until I "inspect element" and then close the inspector window or zoom in/out. It's not an issue with the "display" CSS property because even ...

Tips for retrieving the label value within a repeater control and storing it in a JavaScript variable

I need help extracting the label value from a repeater control and storing it in a JavaScript variable <asp:Repeater ID="rep_tskAttachments" runat="server" OnItemDataBound="rep_tskAttachments_ItemDataBound"> < ...

Customize Material UI (MUI) Autocomplete with preset initial selections

My goal is to develop a unique MUI Autocomplete feature that showcases a series of numbers from 1 to 50. Upon user selection, the component should initially only show numbers 1, 6, 10, 12, and 24. If the user inputs '1', it should then display al ...

Tips for creating fonts that adjust depending on the length of characters

Is there a way to adjust the font size of a paragraph based on the space available in its containing div, depending on the length of characters? For instance: p{ font-size:15px; } <div class="caption"> <p>Lorem ipsum dolor sit amet, consect ...

Nested routes are arranged in the depths and a variety of components appear depending on the path of the

I've encountered a situation where I have deeply nested routes in my routes.js file. The code snippet below shows that depending on the route, I need to render different components. For instance, if the route is for products, I should render the Produ ...

Ways to incorporate smooth transitions to content using CSS

I recently created a website for a competition and I am looking to make the text change when a user hovers over a link. While I have managed to achieve the text change, I now want to add a transition to it. I have only used CSS to change the code. Can some ...

Preserving classes in JQuery after making AJAX requests

Before we proceed, it's important to note that I am unable to modify any of the existing calls, code, or functions. This means I must come up with a workaround solution. So, here's the situation: I have a form containing various fields and a dro ...

What is the best way to assign my function to dynamically generated cards in vanilla JavaScript using event delegation?

I've been experimenting with a card flip feature on dynamically generated elements. The first function I created only applied to the template, so I tried delegating the event to an existing HTML element. However, it's not functioning as expected. ...

Upon initial login, React fails to retrieve notes

I developed a note-taking React app using the MERN stack with React Router DOM v6. When I initially visit the website, I am directed to the login page as intended. However, upon logging in, the page refreshes but does not redirect to the home page. This is ...

AngularJS: Struggling to display modal window with minified AngularJS code

I have successfully created a model dialog using the following JavaScript code, but when I minify the script, I encounter an error preventing the model dialog from opening. The error message states: Error: [$injector:unpr] Unknown provider: aProvi ...

Tips for launching different web browsers via hyperlinks?

My app has a link that I want mobile users from apps like LinkedIn to open in a browser such as Safari. I attempted this: <a href="safari-https://meed.audiencevideo.com">May open on Safari</a>' However, when I click the link, it opens i ...