Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

There's an attribute in tailwind for accomplishing that.

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda