With React, what is the proper way to make functions on scroll?
For example if user scrolls 500px from the top I would like console to log something. What is the best way to do this?
You would have to use DOM to set up a scroll event listener. Take this example:
import React from 'react';
export default class App extends React.Component {
componentDidMount() {
document.addEventListener('scroll', this.onScroll);
}
componentWillUnmount() {
document.removeEventListener('scroll', this.onScroll);
}
onScroll() {
var scrollY = window.scrollY;
if (scrollY === 500) {
console.log(`Scrolled ${scrollY} px`);
}
}
render() {
return (
<main>
<div>Some content</div>
{ this.props.children }
<main>
);
}
}
This code example should give you a good idea on where to take your app. I hope that helps.
You will likely want to subscribe to the scroll event on window.
To attach a listener, you are going to call addEventListener and pass it a function:
window.addEventListener('scroll', someFunction);
Now, as to when React comes into play, you will probably want to attach the listener in the componentDidMount hook of your top-level component:
class App extends React.Component {
constructor() {
super();
this.handleScroll = this.handleScroll.bind();
},
handleScroll(evt) {
const fromTop = window.scrollY;
},
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
}