In my NextJS project, I have two main pages - the Home page and the Leaderboard page. The navigation bar code looks like this:
<div className={styles.navItem}>
<Link href="/">
<a className={styles.navLinks} onClick={toggle}>
Home
</a>
</Link>
</div>
<div className={styles.navItem} onClick={toggle}>
<Link href="/">
<a
className={styles.navLinks}
onClick={setTimeout((e) => {
document.getElementById("about") &&
document
.getElementById("about")
.scrollIntoView({ behavior: "smooth", block: "end" });
}, 2000)}
>
About Us
</a>
</Link>
</div>
<div className={styles.navItem} onClick={toggle}>
<Link href="/">
<a
className={styles.navLinks}
onClick={setTimeout((e) => {
document.getElementById("program") &&
document
.getElementById("program")
.scrollIntoView({ behavior: "smooth", block: "end" });
}, 2000)}
>
Program Overview
</a>
</Link>
</div>
<div className={styles.navItem}>
<Link href="/leaderboard/">
<a className={styles.navLinks} onClick={toggle}>
Leaderboard
</a>
</Link>
</div>
I tried using a delay with setTimeout
to ensure that when clicking on a link in the navbar, it would first take me to the homepage and then smoothly scroll to the desired section after 2 seconds. However, I encountered an error saying document is not defined
. Additionally, upon reloading the page, it automatically smooth-scrolls to #program
without any interaction. How can I resolve this issue?
ERROR (ON TERMINIAL)
error - components/main/Nav/MenuRight.js (18:23) @ Timeout.eval [as _onTimeout]
ReferenceError: document is not defined
16 | <Link href="/">
17 | <a
> 18 | className={styles.navLinks}
| ^
19 | onClick={() =>
20 | setTimeout((e) => {
21 | document.getElementById("about") &&