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 :) .