I'm trying to integrate the ScrollReveal library into my Next.js app. I'm encountering an error when I use ScrollReveal inside a useEffect
hook.
The error message is:
ReferenceError: document is not defined
I understand that this error typically occurs when trying to access the DOM in a non-browser environment, but I'm unsure how to resolve this issue specifically within a Next.js app.
Here's what the relevant part of my code looks like:
import { useEffect } from 'react';
import ScrollReveal from 'scrollreveal';
function MyComponent() {
useEffect(() => {
const sr = ScrollReveal();
sr.reveal('.my-element', {
// ... options
});
}, []);
return (
<div className="my-element">
{/* ... component content */}
</div>
);
}
export default MyComponent;
I've tried using useLayoutEffect instead of useEffect, but the issue persists. I've also seen suggestions to conditionally check for window before using ScrollReveal, but that didn't seem to work either.
Could someone please guide me on how to properly integrate ScrollReveal within a Next.js app to avoid this error? I would greatly appreciate any insights or solutions to resolve this issue.
Thank you in advance for your help!
ScrollReveal doesn't seem to be Next.js and server-side rendering friendly. The library seems to execute browser-specific code on import.
You could fix your issue with lazy loading:
// app/page.js
import dynamic from "next/dynamic";
const MyComponent = dynamic(() => import("./MyComponent"), {
ssr: false,
});
export default function Page() {
return <MyComponent />;
}