0

So when I do (window?.innerHeight || 420) in the case of SSR which translates to

(((_window = window) === null || _window === void 0 ? void 0 : _window.innerHeight) || 420)

I would still get

referenceError: window is not defined

since Javascript has this werid semantics where you have to assign undefined to something that is not defined or you'd have to resort to using bulky expressino like typeof window === 'undefined'

i.e.

window = typeof window === 'undefined' ? undefined : window

So in the settings of frameworks like nextJs, where global variable is not supported, how can I hack things up to include the above defeintion globally so window's optinonal chainning can reliably work across all places?

Archy Will He 何魏奇
  • 9,589
  • 4
  • 34
  • 50
  • 1
    You can't make this truly global in next since window will never be defined in getServerSideProps, getStaticPaths, and getStaitcProps since they always run on the server. Check out this answer and thread - there are env, hooks, and libraries recommended that all could do what you need. https://stackoverflow.com/a/42009294/15304814 – Sean W Apr 10 '21 at 15:59

1 Answers1

1

Since SSR is running in the server, not the browser, window will not be available until the page is loaded. You can get the window object in React's lifecycle methods like useEffect or componentDidMount.

ultrayam
  • 134
  • 8