DEV Community

Louis Facun
Louis Facun

Posted on

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️