How to Implement Sticky Navigation in Next.js/React.js with react-intersection-observer

louisfacun

Louis Facun

Posted on September 25, 2024

How to Implement Sticky Navigation in Next.js/React.js with react-intersection-observer

Introduction

Sticky navigation can enhance user experience by keeping important navigation elements accessible as users scroll. In this tutorial, I’ll show you how to implement different sticky navigation in Next.js/React.js using the react-intersection-observer library.

Note: This approach is particularly useful if you want to show a different component or navigation design when the original non-sticky navigation becomes hidden.

Step 1: Install the Package

First, you need to install the react-intersection-observer package. You can do this using npm:

npm install react-intersection-observer

Step 2: Implement the Code

import { useInView } from 'react-intersection-observer';

const MyComponent = () => {
  const { ref, inView } = useInView({ threshold: 0 });

  return (
    <div>
      <div className={`fixed top-0 z-30 ${inView ? "hidden" : "block"}`}>
        {/* Sticky nav (uses tailwind css class) */}
      </div >
      <div ref={ref}>
        {/* Non sticky nav */}
      </div>
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

Explanation

  1. useInView Hook: This hook helps you track the visibility of an element. When the element referenced by ref is in view, inView will be true.
  2. Threshold: Setting the threshold to 0 means the callback will trigger as soon as any part of the element is visible.

Demo:

Demo of the code

💖 💪 🙅 🚩
louisfacun
Louis Facun

Posted on September 25, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related