A Loading Button With React Native

Created At: 2023-01-06 08:19:43 Updated At: 2023-01-06 08:21:15

The app we are going to make has a button in the center of the screen. When the button is pressed, its background color will change and a loading indicator will show up. If you hit the button again, the loading process will stop and everything will be back to the way it was in the beginning.

This article walks you through a complete example of implementing a button with a loading indicator inside. We will write code from scratch with only the built-in components of React Native including TouchableOpacityActivityIndicatorView, etc. No third-party libraries are required and need to be installed

// App.js
import React, { useState } from "react";
import {
  Text,
  StyleSheet,
  View,
  ActivityIndicator,
  TouchableOpacity,
} from "react-native";

export default function App() {
  const [isLoading, setIsLoading] = useState(false);

  // This function will be triggered when the button is pressed
  const toggleLoading = () => {
    setIsLoading(!isLoading);
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={toggleLoading}>
        <View
          style={{
            ...styles.button,
            backgroundColor: isLoading ? "#4caf50" : "#8bc34a",
          }}
        >
          {isLoading && <ActivityIndicator size="large" color="yellow" />}
          <Text style={styles.buttonText}>
            {isLoading ? "Stop Loading" : "Start Loading"}
          </Text>
        </View>
      </TouchableOpacity>
    </View>
  );
}


// Just some styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: "column",
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  button: {
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-evenly",
    alignItems: "center",
    width: 240,
    height: 70,
    borderWidth: 1,
    borderColor: "#666",
    borderRadius: 10,
  },
  buttonText: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 20
  },
});

Comment

  • r
    ra2886380@gmail.com

    2024-10-28 09:02:53

    you need to add disabled state to prevent button to be pressed unloading

    Author response:

    Are you learning react and flutter together?

  • r
    ra2886380@gmail.com

    2024-08-22 09:04:44

    ioi

  • r
    ra2886380@gmail.com

    2024-08-22 09:04:39

    oio

  • r
    ra2886380@gmail.com

    2024-08-22 09:04:37

    oio

  • r
    ra2886380@gmail.com

    2024-07-31 13:10:41

    Vvvvvg

  • r
    ra2886380@gmail.com

    2024-07-31 13:10:37

    Vg

Add Reviews