reactjsdomundefinedserver-side-renderingfreshjs

Why does the error "document is not defined" still happen when I check for its falsiness already?


I'm using Deno Fresh. In routes/indes.jsx I have:

import Test from "../islands/test.jsx";

export default function App() {
    return <Test></Test>

And in islands/test.jsx I have:

export default function Test() {
  if (undefined) {
    return <span>yo</span>
  } 
  return <span>hi</span>
}

It renders fine. However, if in line 2 it's if (document), then the error document is not defined shows up. Why is that?


Solution

  • In this case it's merely a variable like any other else. If you replace document with any variable of your choice, say if (a) without defining a first, then the same error will happen. Even though the code editor has special treatment on the document variable and not highlight error like other else.

    Use if (globalThis.document) instead, to specify that document is a property of an always existing globalThis.