Published on

How to Make a Sticky Nav Bar - React & NextJS

Authors

We will be learning how to make a header or navigation bar follow you down the page for a more dynamic flow on your webpages.

This helps with things like making your site much more nice to navigate around on. We are currently (as of writing) using this same technique because it allows the reader to easily change themes, look up new articles with the search feature, etc.

A Little Difference in React and NextJS

Okay, so we are focused on the React and NextJS sides of things, as these have become somewhat of the industry standards and practices now, so we will guide you on how to set up your sticky navigation for your next project. With React and NextJS, you will need to approach this a little differently because even when you are using―

'use client'

This will not be enough, because this doesn't mean that the page is only rendered on the client; the server will still render the page and will throw a hydration error if you are trying to use window.scrollY exclusively outside of a useEffect function because the server doesn't have a window to define.

This is where 'useEffect' comes into play.

useEffect(() => {
    const options = { passive: true }
    const changeNav = () => {
      if (window.scrollY >= 25) {
       /* Code when page is scrolled down */
      } else {
        /* Code when page has no scroll down */
      }
    }
    /* these liten for the event between load and scroll */
    window.addEventListener('load', changeNav, options)
    window.addEventListener('scroll', changeNav, options)
    changeNav()
    return () => {
      window.removeEventListener('load', changeNav)
      window.removeEventListener('scroll', changeNav)
    }
  })

Although you are not limited to useEffect() (recommended), you can also tell the page that whenever you import it, it should not use SSR server-side rendering.

This can be done by using a dynamic import whenever you are importing the component.

const HeaderNav = dynamic(
  () => import('../components/location'),
  { ssr: false }
)

You will maybe have some use cases where you just want the code to run only client-side (not recommended).

You can use the following code in your function, and it will only run if the window is defined.

if(typeof window !== 'undefined'){
window.scrollY >= 25 ? 'Scrolled' : 'No-scroll'
}

// another way to write it below
if(typeof window !== 'undefined'){
if(window.scrollY >=25) {
    return 'Scrolled'
} else {
    return 'No-scroll'
}
}

I Hope This Helps You !

This should get the job done for you, but you will have to add to the code to get the desired effect that you are going for !