How to show hide Activity Indicator spinner on button click in React Native

Introduction :

In this React Native tutorial program, we will learn how to show/hide one Activity Indicator based on a button click. The user will click one button to show the loading spinner and click it again to hide it.

ActivityIndicator :

ActivityIndicator component is used to show one activity indicator. It has one prop called animating based on which, it shows/hides the indicator spinner.

In the below program, we will add one button, on click, it will change the state of animating.

React Native program :

Create one sample react-native program and update the App.js file as like below :

import React, {useState} from 'react';
import {
  SafeAreaView,
  StatusBar,
  StyleSheet,
  View,
  ActivityIndicator,
  Button,
} from 'react-native';

const App = () => {
  const [indicator, setIndicator] = useState(false);
  
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView style={styles.container}>
        <View style={styles.parent}>
          <ActivityIndicator size="large" color="blue" animating={indicator} />
          <View style={styles.clickbutton}>
            <Button
              title="Click Me"
              onPress={() => {
                setIndicator(!indicator);
              }}
            />
          </View>
        </View>
      </SafeAreaView>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  parent: {
    flex: 1,
    justifyContent: 'center',
  },
  clickbutton: {
    marginTop: 20,
  },
});

export default App;

Explanation :

  1. We are using react hook here. indicator is a boolean value initialized as false. This value is passed as animating to control the indicator show/hide states.

  2. Button will invoke the function defined for onPress. It will change the value of the_ indicator_.

  3. Clicking on the button will toggle the ActivityIndicator.

Output :

It will give one output like below :

ios activityindicator example