I need to basically rewrite this codepen in react.
function resizeHeaderOnScroll() {
const distanceY = window.pageYOffset ||
document.documentElement.scrollTop,
shrinkOn = 200,
headerEl = document.getElementById('js-header');
if (distanceY > shrinkOn) {
headerEl.classList.add("smaller");
} else {
headerEl.classList.remove("smaller");
}
}
window.addEventListener('scroll', resizeHeaderOnScroll);
I need to basically rewrite this codepen in react. https://codepen.io/lili2311/pen/dJjuL
function resizeHeaderOnScroll() {
const distanceY = window.pageYOffset ||
document.documentElement.scrollTop,
shrinkOn = 200,
headerEl = document.getElementById('js-header');
if (distanceY > shrinkOn) {
headerEl.classList.add("smaller");
} else {
headerEl.classList.remove("smaller");
}
}
window.addEventListener('scroll', resizeHeaderOnScroll);
Share
Improve this question
asked May 25, 2018 at 2:00
zeddyzeddy
311 silver badge4 bronze badges
2 Answers
Reset to default 6A simple implementation would include
- adding the scroll event listener to ponentDidmount,
- changing class to className,
- adding html to render()
- including the css
I have created the same for you in codesandbox.io
Ok here is my try. Not sure if it going to work properly or not but It will give you a general idea how to build it in react.
//Create a navbar ponent
class Navbar extends Component {
constructor() {
super();
//In the state you can keep track of the class you want to add to the element
this.state = {
class: "" //For now its empty or you can give it a default class.
}
}
//use the lifecycle methods to trigger the getWindowHeight method.
ponentDidMount(){
() => {
window.addEventListener('scroll', this.getWindowHeight);
}
}
ponentWillUnmount(){
() => {
window.removeEventListener('scroll', this.getWindowHeight);
}
}
//then create the method
getWindowHeight = () {
const distanceY = window.pageYOffset ||
document.documentElement.scrollTop
const shrinkOn = "200px";
//Now In the condition change the state to smaller so if the condition is true it will change to smaller otherwise to default state
if (distanceY > shrinkOn) {
this.setState({
class: "smaller"
})
}
}
render() {
return (
//Now in the element you can add the state to the class as well as add event to the onScroll
<navbar className={this.state.class} >
</navbar >
)
}