In a previous post we discussed why and how to safely use the
document object and receiving a
ReferenceError: document is not defined error then there is a good chance you have run into a similar problem. This object is actually a property of the
window object so many of the same causes and solutions apply. You’ll want to ensure that you really need to use it first and if you do, add some logic to safely access the variable.
document object gives you many of the properties and methods you need to be able to do just that. Some of those include:
document is not defined error mentioned above. For example, if you are working with a server-side rendered (SSR) application using Next.js, Gatsby.js, or something similar, you may run into this error while working on the frontend.
The first thing you will want to do is make sure you truly need to use the
document object. It is fairly easy to safely access the
document object if you decide that you need it based on your use case. For example, to get a web page’s title only when you are in a browser environment:
Often times you can just replace your usage of
document rather than trying to safely access it. In React, for example, you may be tempted to access a DOM element using
document.getElementById(). Fortunately, React has its own concept called Refs for handling DOM elements that you might consider using instead. Doing so means you will not have to worry about the
document possibly being undefined (if you are using Next.js or Gatsby.js, for example).
There are many benefits to using Refs in React other than simply replacing
document usage in your app. Understanding the entirety of their potential use is out of the scope of this post but you can start your learning with the official React documentation here.
document.getElementById() with Refs do the following:
As powerful as it is, the
document object does still have its pitfalls — especially if you try to use it in a Node.js environment or with an app that is built in a Node.js environment before running in the browser. If you follow the steps in this article you can either replace or properly use
document and be back to creating your web app in no time.