Note!
Already compiled via link:https://codesandbox.io/s/sticky-header-dyews?file=/src/App.js
after reading lots of js code that accomplishes this, I achieved this like so...
.header {position: sticky;top: 0px;z-index: 1;}
In react you need to set the class by calling a useState
function.
You can set the listener for this in a useEffect
that runs once on component render.
import React, { useEffect, useState } from "react";const Header = () => {const [sticky, setSticky] = useState("");// on render, set listeneruseEffect(() => {console.log("hello");window.addEventListener("scroll", isSticky);return () => {window.removeEventListener("scroll", isSticky);};}, []);const isSticky = () => {/* Method that will fix header after a specific scrollable */const scrollTop = window.scrollY;const stickyClass = scrollTop >= 250 ? "is-sticky" : "";setSticky(stickyClass);console.log(stickyClass);};const classes = `header-section d-none d-xl-block ${sticky}`;return (<><header className={classes}>..add header code</header></>);};export default Header;
Sandbox here: https://codesandbox.io/s/sticky-header-forked-ybo6j9
Most of this code referenced from this answer: https://stackoverflow.com/a/69944800/271932 (which has correct CSS but not react code)
position: sticky
is realy cool.
Its compatibility is also ok
Just pay some attention to the parent element's height, and most of time, you may need to cooperate it with React.Fragment
.