I want to implement infinite scroll in my app.
I found https://github.com/bvaughn/react-virtualized, but it's a bit heavy. I want to use a simple and thin one, and then I found react-infinite
react-infinite
https://github.com/seatgeek/react-infinite
sample code for react-infinite
with a create-react-app environment
- using create-react-app
- using ES6 syntax
- without React.createClass
NOTE
- this sample code has elements in React Component's state
It's a bit weird.
code
import React, { Component } from 'react';
import Infinite from 'react-infinite';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<InfiniteList />
</div>
);
}
}
class ListItem extends React.Component {
render () {
return (
<div className="infinite-list-item">
List Item {this.props.num}
</div>
);
};
};
class InfiniteList extends React.Component {
constructor (props) {
super(props);
this.state = {
elements: this.buildElements(0, 100),
isInfiniteLoading: false
};
}
buildElements (start, end) {
let elements = [];
for (let i = start; i < end; i++) {
elements.push(<ListItem key={i}/>)
}
return elements;
}
handleInfiniteLoad () {
let that = this;
this.setState({
isInfiniteLoading: true
});
setTimeout(function() {
let elemLength = that.state.elements.length,
newElements = that.buildElements(elemLength, elemLength + 1000);
that.setState({
isInfiniteLoading: false,
elements: that.state.elements.concat(newElements)
});
}, 2500);
}
elementInfiniteLoad () {
return <div className="infinite-list-item">
Loading...
</div>;
}
render () {
return <Infinite elementHeight={40}
containerHeight={250}
infiniteLoadingBeginBottomOffset={200}
onInfiniteLoad={this.handleInfiniteLoad}
loadingSpinnerDelegate={this.elementInfiniteLoad()}
isInfiniteLoading={this.state.isInfiniteLoading}
>
{this.state.elements}
</Infinite>;
}
};
export default App;