1
votes

I'm trying to create a PDF viewer on my nextjs static page but i dont know how! hope you guys can help me solving this error or showing one other way to do this. (I'm new to Next.js) I was following this working example here

index.js

import SiteLayout from "../../components/SiteLayout";
import React from 'react';
import ReactDOM from "react-dom";
import Viewer from "../resume/viewer.js";

export default function Resume({ resume }) {
  return (   
    <div>
      <Viewer />
    </div> 
  );
}

viewer.js

import React, { useRef, useEffect } from "react";
import WebViewer from "@pdftron/webviewer";

const Viewer = (props) => {
  const viewer = useRef(null);

  useEffect(() => {       
    WebViewer({
      path: "/lib",
      initialDoc: "/pdf/GustavoMorilla.pdf"
    }, viewer.current);
  }, []);

  return (
    <div className="Viewer">
      <div className="header">React sample</div>
      <div className="webviewer" ref={viewer}></div>
    </div>
  );
};

export default Viewer;
2
Where are you rendering Resume? You are getting the error because of this ReactDOM.render(<Viewer />) - lissettdm
for a Navbar item "resume" the user will be redirected to this page via "href" ... I need a way to load the page and call the Viewer component that contains the webviewer. Dont know if this react DOM declaration is correct. - Gustavo Morilla
Why do you use ReactDOM.render(<Viewer /> instead of <Viewer/>? - lissettdm
Are you missing to pass viewer.current as second argument in WebViewer function? - lissettdm
Try to add more details about the error (line, file, etc) because I don't see anything wrong - lissettdm

2 Answers

2
votes

When you import @pdftron/webviewer some code is running even though you haven't called the WebViewer function. The useEffect callback doesn't run in SSR. You can use Dynamic Imports there to import the module:

useEffect(() => {    
    import('@pdftron/webviewer')
     .then(WebViewer) => {
        WebViewer({
          path: "/lib",
          initialDoc: "/pdf/GustavoMorilla.pdf"
        }, viewer.current);
    }) 
}, []);
2
votes

WebViewer needs the window object to work. In nextjs there is a prerender phase server side and on that side window is not defined.

To solve your problem you can use next/dynamic in viewer.js

import dynamic from 'next/dynamic';
const WebViewer = dynamic(() => import('@pdftron/webviewer'), {ssr: false});

Alternatively you can import Viewer in index.js with dynamic import

import dynamic from 'next/dynamic';
const Viewer = dynamic(() => import('../resume/viewer.js'), {ssr: false});