Co.tibi
Co.tibi

Reputation: 53

Sticky navbar with React Nextjs

I'm trying to setup a sticky navbar with nextjs but the resulting navbar is not working like it should. Can anyone help with the code below?

import React, { useEffect } from 'react'
import styles from './navbar.module.css'

const Navbar = () => {
    const [scrolled, setScrolled] = React.useState(false);

    const handleScroll = () => {
        const offset = window.scrollY;

        if (offset > 200) {
            setScrolled(true);
        }
        else {
            setScrolled(false);
        }
    }
    useEffect(() => {
        window.addEventListener('scroll', handleScroll)
    })


    return (
        <div className={scrolled ? styles.scrolled : styles.navbar}>
            <ul className={styles.ul}>
                Something
            </ul>
            Navbar
        </div>
    )

};

export default Navbar;

Upvotes: 2

Views: 10021

Answers (2)

Roman Mkrtchian
Roman Mkrtchian

Reputation: 3006

If what you want is to have a sticky navbar, you can do it with pure CSS with position: sticky like this:

header, nav, main {
  padding: 1.7rem 1rem;
}

header {
  background-color: #d99;
}

nav {
  position: sticky;
  top: 2rem;
  background-color: #9d9;
}

main {
  height: 100vh;
  background-color: #99d;
}
<header>
Header
</header>
<nav>
  Navbar
</nav>
<main>
  Main
</main>

Upvotes: 2

doteth
doteth

Reputation: 83

I'm not sure if this would fix your problem, but you could try changing your useEffect to have an empty dependency array at the end of it so that it runs when the component mounts, like this:

useEffect(() => {
    window.addEventListener('scroll', handleScroll)
}, [])

Upvotes: 0

Related Questions