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 :) .
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
There's an attribute in tailwind for accomplishing that.