Created
November 4, 2019 22:01
-
-
Save BretCameron/839ad5854fc4ef6387deade3a898180f to your computer and use it in GitHub Desktop.
A React component with a very simple implementation of infinite scroll (written in Typescript)
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 './App.css'; | |
const debounce = (fn: Function, time: number) => { | |
let timeout: NodeJS.Timer; | |
return function(...args: any[]) { | |
const functionCall = function(this: any) { | |
fn.apply(this, args); | |
clearTimeout(timeout); | |
}; | |
timeout = setTimeout(functionCall, time); | |
}; | |
}; | |
class App extends React.Component { | |
state = { | |
n: 20 | |
}; | |
componentDidMount() { | |
document.addEventListener('scroll', this.trackScrolling); | |
} | |
componentWillUnmount() { | |
document.removeEventListener('scroll', this.trackScrolling); | |
} | |
trackScrolling = debounce(() => { | |
if ( | |
document.querySelector('body') && | |
window.pageYOffset + window.innerHeight === | |
document.querySelector('body')!.offsetHeight | |
) { | |
console.log('Reached Bottom'); | |
this.setState({ n: this.state.n + 10 }); | |
} | |
}, 100); | |
render() { | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
{Array(this.state.n) | |
.fill(1) | |
.map((el, i) => { | |
return ( | |
<p key={i} style={{ background: '#555', padding: '20px 40px' }}> | |
stuff | |
</p> | |
); | |
})} | |
</header> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment