Created
November 25, 2018 15:57
-
-
Save jitinmaher/ead53030c8a601082507facdffa7ede2 to your computer and use it in GitHub Desktop.
This gist creates sticky header implemented in react classes
This file contains hidden or 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, { Component } from "react"; | |
import SomeRandomText from "./SomeRandomText"; | |
import "./styles.css"; | |
export default class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
headerText: "I am not fixed :(" | |
}; | |
this.scrollCallback = this.scrollCallback.bind(this); | |
this.fixedText = "I am fixed :)"; | |
this.whenNotFixed = "I am not a fixed header :("; | |
} | |
setHeaderText(text) { | |
this.setState({ | |
headerText: text | |
}); | |
} | |
scrollCallback() { | |
const { headerText } = this.state; | |
const header = document.getElementById("myHeader"); | |
const sticky = header.offsetTop; | |
if (window.pageYOffset > sticky) { | |
header.classList.add("sticky"); | |
if (headerText !== this.fixedText) { | |
this.setHeaderText(this.fixedText); | |
} | |
} else { | |
header.classList.remove("sticky"); | |
if (headerText !== this.whenNotFixed) { | |
this.setHeaderText(this.whenNotFixed); | |
} | |
} | |
} | |
componentDidMount() { | |
this.scrollCallback = window.addEventListener( | |
"scroll", | |
this.scrollCallback | |
); | |
} | |
componentWillUnmount() { | |
window.removeEventListener("scroll", this.scrollCallBack); | |
} | |
render() { | |
const { headerText } = this.state; | |
return ( | |
<div> | |
<header className="header">HEADER</header> | |
<SomeRandomText /> | |
<header id="myHeader" className="header"> | |
{headerText} | |
</header> | |
<SomeRandomText /> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment