Last active
September 15, 2023 07:29
-
-
Save jsdf/6930c0211e0dc5bf0227 to your computer and use it in GitHub Desktop.
React Native pull down to refresh ListView
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
| var React = require('react-native') | |
| var { | |
| ListView, | |
| ActivityIndicatorIOS, | |
| StyleSheet, | |
| View, | |
| Text, | |
| } = React | |
| var RefreshableListView = React.createClass({ | |
| getInitialState() { | |
| return { | |
| reloading: false, | |
| } | |
| }, | |
| handleScroll(e) { | |
| // must be less than 40 px due to ScrollView bug (event only fires onces) | |
| // TODO: fix this when onScroll works properly | |
| if (e.nativeEvent.contentOffset.y < -40) { | |
| this.reloadData() | |
| } | |
| this.props.onScroll && this.props.onScroll(e) | |
| }, | |
| reloadData() { | |
| if (this.willReload || this.state.reloading) return | |
| this.willReload = true | |
| Promise.all([ | |
| this.props.loadData(), | |
| new Promise((resolve) => this.setState({reloading: true}, resolve)), | |
| new Promise((resolve) => setTimeout(resolve, 300)), | |
| ]).then(([data]) => { | |
| this.willReload = false | |
| this.setState({reloading: false}) | |
| }) | |
| }, | |
| renderHeader() { | |
| if (this.state.reloading) { | |
| return ( | |
| <View style={[styles.container, styles.wrapper]}> | |
| <View style={[styles.container, styles.loading]}> | |
| <Text>{this.props.refreshDescription}</Text> | |
| <ActivityIndicatorIOS /> | |
| </View> | |
| </View> | |
| ) | |
| } else { | |
| return null | |
| } | |
| }, | |
| render() { | |
| return ( | |
| <ListView | |
| {...this.props} | |
| onScroll={this.handleScroll} | |
| renderHeader={this.renderHeader} | |
| /> | |
| ) | |
| } | |
| }) | |
| var styles = StyleSheet.create({ | |
| wrapper: { | |
| height: 60, | |
| marginTop: 10, | |
| }, | |
| container: { | |
| flex: 1, | |
| justifyContent: 'space-around', | |
| alignItems: 'center', | |
| backgroundColor: 'white', | |
| }, | |
| loading: { | |
| height: 60, | |
| }, | |
| }) | |
| RefreshableListView.DataSource = ListView.DataSource | |
| module.exports = RefreshableListView |
In action (from ReactNativeHackerNews):
Installable version: react-native-refreshable-listview
Hi, it doesn't work on android. ^_^
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

usage example