Skip to content
Related Articles

Related Articles

Improve Article

How to implement Swipe to Refresh in React Native ?

  • Last Updated : 19 Jul, 2021

In this article, we will look at how we can use the Swipe Down to Refresh feature in React Native. In applications that show real-time data to the users such as crypto values or availability of a food item in a Food Ordering app, users can do a vertical swipe down on the app to manually refresh the data from the server. 

We will use RefreshControl component inside a Scroll View to add the pull to refresh functionality.

Creating React Native App and Installing Module:

  • Step 1: Open your terminal and install expo-cli by the following command.

    npm install -g expo-cli

     



  • Step 2: Now create a project by the following command.

    expo init demo-app
  • Step 3: Now go into your project folder i.e. demo-app

    cd demo-app

Project Structure: It will look like the following.

Implementation: In this example, we will create a Text component inside a ScrollView which will change its color when the user swipes down on the app. When the user swipes down, the onRefresh function is called which turns the refreshing controlled prop to be true. Hence, the user can now see a loading icon and after 2000 ms i.e. 2 seconds, the color of the button is changed to green and the refreshing controlled prop is changed to be false. This stops the loading icon to disappear after the execution of the function.

Filename: App.js

App.js




import React, {useState} from 'react';
import {ScrollView, StyleSheet, Text, 
   View, RefreshControl} from 'react-native';
  
const App = () => {
  const [color, changeColor] = useState('red');
  const [refreshing, setRefreshing] = React.useState(false);
  
  const onRefresh = () => {
    setRefreshing(true);
    setTimeout(() => {
      changeColor('green');
      setRefreshing(false);
    }, 2000);
  };
  return (
    <ScrollView
      refreshControl={
        <RefreshControl refreshing={refreshing} 
          onRefresh={onRefresh} />
      }
      style={styles.container}>
      <View
        style={{
          marginTop: 200,
          alignSelf: 'center',
          padding: 20,
          backgroundColor: color,
        }}>
        <Text style={{color: 'white'}}>
          Swipe Down to Change Color !
        </Text>
      </View>
    </ScrollView>
  );
};
  
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});
  
export default App;

Start the server by using the following command.

npm run android

Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again.




My Personal Notes arrow_drop_up
Recommended Articles
Page :