#document is not defined
1 messages · Page 1 of 1 (latest)
Hi @lyric river. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
The error "document is not defined" typically occurs when you try to access the document object on the server-side in a Next.js application. The document object is part of the Browser API and is not available on the server-side.
In Next.js, if you're trying to use the document object inside a component, you should do so within a useEffect hook or any other lifecycle method that runs on the client-side. Here's an example:
import { useEffect } from 'react';
export default function Check() {
useEffect(() => {
const body = document.body;
if (body.classList.contains("dark")) {
return true;
} else {
return false;
}
}, []);
}
In the above code, the useEffect hook ensures that the code inside it will only run on the client-side after the component has been rendered, thus ensuring that the document object is available.
For more information, you can refer to the discussion on this issue on the Next.js GitHub page here (https://github.com/vercel/next.js/issues/44014) and here (https://github.com/vercel/next.js/issues/49139).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@lyric river kapa.ai is still learning and improving, please let us know how it did by reacting below
@brazen valve Argument of type '() => boolean' is not assignable to parameter of type 'EffectCallback'.
Type 'boolean' is not assignable to type 'void | Destructor'.ts(2345)
Let me check the knowledge base for you. One moment! :books:
The error message you're seeing is because the function you're passing to useEffect is expected to return either nothing (void) or a cleanup function (Destructor). However, your function is returning a boolean value, which is not allowed.
The useEffect hook is not meant to return a value that you can use elsewhere in your component. It's used for running side effects, like fetching data, manipulating the DOM directly, setting up subscriptions, etc.
If you want to set a state based on whether the body has a class "dark", you should use the useState hook. Here's an example:
import { useEffect, useState } from 'react';
export default function Check() {
const [isDark, setIsDark] = useState(false);
useEffect(() => {
const body = document.body;
setIsDark(body.classList.contains("dark"));
}, []);
// Now you can use isDark in your component
}