Hello Friends đź‘‹,

Welcome to Infinitbility.

When we are calling servers and any third-party API’s then we have to make sure users will not press multiple times’ buttons and that’s some people show loader and some disabled-buttons.

Today, we will see how we can disable a button when anyone presses a button.

Basically, we are going to create a state and we will disable it when clicking on a button plus we also condition a button if the state isDisabled is true we will disable a button.

To possible this feature, the react-native button provides disabled option when we will pass true button should go automatically in disabled mode and when we change to false then button comes to enable mode.

Let’s try the real-life example.

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

const App = () => {
    const [isDisabled, setIsDisabled] = useState(false);
    
    const doYourTask = () => {
      setIsDisabled(true);
    }
    
    return (
    <View style={styles.container}>
      <Button
        title="Press me"
        disabled={isDisabled}
        onPress={() => doYourTask()}
      />
    </View>)
};

const styles = StyleSheet.create({
  container: {
    right: 10,
    left: 10,
    position: 'absolute',
    bottom: 10,
  }
});

export default App;

Try it yourself

In the above example, we have called a function doYourTask() and disabled button with help of the state, and when you want to enable it after your task call setIsDisabled(false).

Thanks for reading…