How to solve ReferenceError: document is not defined in react-quill - Next.js

Cover Image for How to solve ReferenceError: document is not defined in react-quill - Next.js
Ali Bentaleb

React quill is a rich text editor which let you type text and applies styles like any microsoft word document inside your browser. This tool is very helpful in order to make text bold, apply italic styles and so on on text that you would like to publish online.

In this tutorial, we will explain how to make it work with React based Framework Next.js, and how to resolve the famous error of ReferenceError: document is not defined

Install ReactQuill

First, we neeed to install the package, to do so:

npm i react-quill

yarn add react-quill

import ReactQuill

Next, to use the rich text editor, we import it in our js files,

import ReactQuill from 'react-quill';

export default function Test() {
	return (
		<div>
			{' '}
			<ReactQuill theme="snow" placeholder="Write description" />
		</div>
	);
}

with this import in Next.js, we will run into the error of ReferenceError: document is not defined since pages are rendered on server side by default.

document is not defined error when importing reactQuill in Next.js

Dynamic import of ReactQuill

To solve this issue in Next.js, we need to dynamically import our react-quill and tell next.js to not render it on the server.

Whenever you encounter the error document is not defined, make sure your JS code is running on client side by making sure that:

  • document is declared within react useEffect hook
  • or by disabling server side rendering by testing first whether document is defined using this way: if ( typeof window !== ‘undefined’) {run your document code }

and not on server side since document is only defined on client browser.

In next.js this can be done by disabling server sire rendering built in function as below:

import dynamic from 'next/dynamic';

const ReactQuill = dynamic(import('react-quill'), {ssr: false});

export default function Test() {
	return (
		<div>
			{' '}
			<ReactQuill theme="snow" placeholder="Write description" />
		</div>
	);
}

Now the import is working fine as we can see on the image below

dynamic import of reactQuill in Next.js

To learn more about dynamic import and how to set off rendering in server side you can check my article in this link

Apply snow theme to ReactQuill

We can also apply some specific themes in our Next.js project by editing our _app.js file so that the theme can be applied in ReactQuill import

//_app.js

import 'react-quill/dist/quill.snow.css';

Conclusion

We have seen how to disable rendering in server side for Next.js so that our React quill can work on client side seamlessly

To display content from react quill, i recommend to check this article

How to display React quill con...How to correctly set environme...


More interesting articles