whimsyBear whimsyBear - 2 months ago 33
React JSX Question

Show an activity indicator at the end of a ListView in React-Native

Looking for a way to append an activity indicator to the end of a ListView when the user has reached the end and the app is querying for more data from a server. I can add the indicator after the ListView but then it always show up.

Answer

You should be able to achieve that by using the onEndReached prop for A ListView. When you reach the end you can render the loader. In my case I used renderFooter to render the loader at the bottom of the list. In my scenario

You can set in the component state an attribute called messagesLoading that you set to true when you start fetching new data and to false when done. Based on that, you can display or not the loading indicator in the footer.

This example partial implementation should give you an idea of how you can do it:

class ThreadDetail extends React.Component {

    constructor () {
        super()
        this.state = {
          loading: false
        }
    }

    loadMoreMessages () {
        this.setState({ loading: true })
        fetchMessagesFromApi()
            .then(() => {
                this.setState({ loading: false })
            })
            .catch(() => {
                this.setState({ loading: false })
            })
    }

    renderFooter () {
        return this.state.loading ? <View><Text>Loading...</Text></View> : null
    }

    render () {
        return <ListView
          renderRow={message => <Message message={message}/>}
          dataSource={this.state.dataSource}
          renderFooter={this.renderFooter.bind(this)}
          onEndReached={this.loadMoreMessages.bind(this)}
          onEndReachedThreshold={10}
          scrollEventThrottle={150} />
    }
}