Bruno Quaresma
Bruno Quaresma

Reputation: 10687

"Document is not defined" Webpack + React on Rails + Server Rendering

Im use react_on_rails gem and im try render the component by the server.

When i use components directly from the app it works OK!

import Hello from "../components/Hello"

ReactOnRails.register({
  Hello
})

But when i try use a package, the app throws error.

import { Ballon } from "foo-package"
import Hello from "../components/Hello"

ReactOnRails.register({
  Ballon,
  Hello
})

ERROR in SERVER PRERENDERING
Encountered error: "ReferenceError: document is not defined"

Someone knows why?

Upvotes: 1

Views: 1472

Answers (2)

Bruno Quaresma
Bruno Quaresma

Reputation: 10687

I found! The 'foo-package' uses a non isomorphic package. Its breaks the server rendering. The package is react-google-chart.

Upvotes: 0

moljac024
moljac024

Reputation: 195

window and document are global variables that are only available in a browser environment.

When you are rendering on the server you don't have that environment. You need to safeguard your code and skip invoking any functions on those objects when you are in a node.js environment. For example:

if (typeof document !== 'undefined') {
  // Do your document thing here
} else {
  console.log("We're on server")
}

Upvotes: 2

Related Questions