Skip to content

Instantly share code, notes, and snippets.

@jitinmaher
Created November 25, 2018 16:00
Show Gist options
  • Save jitinmaher/b3eeb2fac2e07ba56911b4662a8789dc to your computer and use it in GitHub Desktop.
Save jitinmaher/b3eeb2fac2e07ba56911b4662a8789dc to your computer and use it in GitHub Desktop.
Sticky header using hooks
import React from "react";
import { useEffect, useState } from "react";
import SomeRandomText from "./SomeRandomText";
import "./App.css";
function App() {
const fixedText = "I am fixed :)";
const whenNotFixed = "I am not a fixed header :(";
const [headerText, setHeaderText] = useState(whenNotFixed);
useEffect(() => {
const header = document.getElementById("myHeader");
const sticky = header.offsetTop;
const scrollCallBack = window.addEventListener("scroll", () => {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
if (headerText !== fixedText) {
setHeaderText(fixedText);
}
} else {
header.classList.remove("sticky");
if (headerText !== whenNotFixed) {
setHeaderText(whenNotFixed);
}
}
});
return () => {
window.removeEventListener("scroll", scrollCallBack);
};
}, []);
return (
<div>
<header className="header">HEADER</header>
<SomeRandomText />
<header id="myHeader" className="header">
{headerText}
</header>
<SomeRandomText />
</div>
);
}
export default App;
@maheshodiveti
Copy link

good example for sticky header.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment