Created
November 25, 2018 16:00
-
-
Save jitinmaher/b3eeb2fac2e07ba56911b4662a8789dc to your computer and use it in GitHub Desktop.
Sticky header using hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good example for sticky header.