最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sticky navbar with React Nextjs - Stack Overflow

programmeradmin11浏览0评论

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;

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;
Share Improve this question asked May 18, 2021 at 18:40 Co.tibiCo.tibi 531 gold badge1 silver badge5 bronze badges 1
  • 1 What do you mean by "not working like it should" ? Can you describe what exactly happens that you don't want, or does not happen that you want ? – Roman Mkrtchian Commented May 18, 2021 at 18:48
Add a ment  | 

2 Answers 2

Reset to default 2

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>

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 ponent mounts, like this:

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

评论列表(0)

  1. 暂无评论