Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
How to create a sticky navbar on scroll in react

I'm trying to add the sticky navbar effect to the navbar of a site when a user scrolls down. i.e I want the navbar to become fixed at the top of the page when the browser is scrolled down a certain height

I'm trying to implement this with react hooks. Here's the code for the navbar

Navbar.js

   import { useEffect, useState } from "react";

    const NavBar = () => {
    // sticky nav
    const [stickyClass, setStickyClass] = useState("");

    function stickNavbar() {
        let windowHeight = window.scrollY;
        setStickyClass("sticky-nav") ? windowHeight > 500 : setStickyClass("");
    }

    useEffect(() => {
        window.addEventListener("scroll", stickNavbar);
    }, []);

return (
        <nav className="relative w-full p-4">
            <div className={`flex w-full flex-row items-center justify-between ${stickyClass}`}>
             navbar content goes here ....
            <div/>
<nav/>

I'm using tailwindcss for styling so there's no external stylesheet, however the sticky-nav class applies some of tailwindcss's utility classes.

components.css

/* Navbar */
.sticky-nav {
    @apply fixed top-0 left-0 w-full shadow-md z-20;
}

I did research it online but nothing really helpful came up, really hoping anyone could help me out here :) .

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try this :

import React, { useState, useEffect } from 'react';

export default function Navbar() {
  const [stickyClass, setStickyClass] = useState('relative');

  useEffect(() => {
    window.addEventListener('scroll', stickNavbar);

    return () => {
      window.removeEventListener('scroll', stickNavbar);
    };
  }, []);

  const stickNavbar = () => {
    if (window !== undefined) {
      let windowHeight = window.scrollY;
      windowHeight > 500 ? setStickyClass('fixed top-0 left-0 z-50') : setStickyClass('relative');
    }
  };

  return <div className={`h-16 w-full bg-gray-200 ${stickyClass}`}>Navbar</div>;
}

Demo (without Tailwinds but same result): Stackblitz

about 4 years ago · Juan Pablo Isaza Report

0

There's an attribute in tailwind for accomplishing that.

https://tailwindcss.com/docs/position#sticky

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!