react-file-viewer icon indicating copy to clipboard operation
react-file-viewer copied to clipboard

Server side render fails with reference to window

Open Dieff opened this issue 6 years ago • 3 comments

I've been trying this component on a web app running on Next.js. The server side rendering of the component fails because on the server (in node) there is no global window object. I receive the following error from Next:

ReferenceError: window is not defined
 |     at /web/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:7:19652
 |     at /web/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:7:19614
 |     at e.exports web/(/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:7:20125)
 |     at Object.<anonymous> web/(/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:22:6013)
 |     at t web/(/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:1:500)
 |     at Object.<anonymous> web/(/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:11:68241)
 |     at t web/(/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:1:500)
 |     at Object.<anonymous> web/(/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:11:84264)
 |     at t web/(/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:1:500)
 |     at /web/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:1:883
 |     at /web/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:1:894
 |     at /web/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:1:143
 |     at Object.<anonymous> web/(/Users/*/devel/synapse/node_modules/react-file-viewer/dist/index.js:1:374)
 |     at Module._compile web/(internal/modules/cjs/loader.js:707:30)
 |     at Object.Module._extensions..js web/(internal/modules/cjs/loader.js:718:10)
 |     at Module.load web/(internal/modules/cjs/loader.js:605:32)

If you want this library to support server side rendering, you will probably have to avoid references to global browser objects that do not exist in Node, or use isomorphic alternatives. Luckily, there is only one place in the core library where window is referenced, in "photo-viewer-wrapper.jsx", which can simply be removed.

This is using react-file-viewer 1.1.0, installed from npm, and nextjs 7.02.

Dieff avatar Jan 22 '19 19:01 Dieff

This doesn't seem to fix the issue.

bryaan avatar Jul 28 '19 06:07 bryaan

I had the same problem, but with only changed that file it doesn't solve the problem, I think you can use React.lazy to lazy load the component, so it only gets rendered when the client wants to render it, I solved mine by doing this

mania25 avatar Oct 01 '19 17:10 mania25

This works @mania25 . Thanks!

Faced this issue in next js build on netlify. Was able to solve this using React.lazy and Suspense.

Ref: https://reactjs.org/docs/code-splitting.html#reactlazy

evojewel avatar Jan 14 '22 15:01 evojewel