How to add Pull Down to Refresh Feature in React Native
Pull down to refresh is a cool feature we usually see in Android apps. It helps users to refresh a list or collection of data. In react native, you can use the RefreshControl component to implement pull down to refresh feature.
The RefreshControl works as a prop for components such as ScrollView, Flatlist etc. See the code snippet given below.
<ScrollView
contentContainerStyle={styles.scrollView}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={['red']}
tintColor="red"
/>
}>
<Text>Pull down to see RefreshControl indicator</Text>
</ScrollView>
The refreshing property accepts a boolean and the onRefresh prop decides what to do while refreshing. The colors prop is for setting color in Android and the tintColor is for setting color in iOS.
See the example given below to know how the RefreshControl component works in ScrollView.
import React, {useState, useCallback} from 'react';
import {
StyleSheet,
Text,
SafeAreaView,
ScrollView,
RefreshControl,
} from 'react-native';
const App = () => {
const [refreshing, setRefreshing] = useState(false);
const onRefresh = useCallback(() => {
setRefreshing(true);
setTimeout(() => {
setRefreshing(false);
console.log('refreshed');
}, 2000);
}, []);
return (
<SafeAreaView style={styles.container}>
<ScrollView
contentContainerStyle={styles.scrollView}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={['red']}
tintColor="red"
/>
}>
<Text>Pull down to see RefreshControl indicator</Text>
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollView: {
flex: 1,
backgroundColor: 'lightblue',
alignItems: 'center',
justifyContent: 'center',
},
});
export default App;
When the user pulls down the screen, refreshing will be set as true and the progress indicator will be shown. When the timeout is finished, refreshing will be set as false and the progress indicator will disappear.
Following is the output.
That’s how you add pull down to refresh feature in react native.