Home > Software engineering >  Disabled Button in React Native
Disabled Button in React Native

Time:03-07

I'm in a login problem trying to disable a interaction with a button. The idea is to disable a submit button when 2 text field are empty, but i have the same result when is empty or not (always clickable, or always not). Below i specific the idea that i have, and how i implement it.

I have two states that stores the values from two text input, then i have a function "isEmpty" that consult if that states are empty (" "). Later, in a button "Submit" i have a property 'disabled' that wich value is the result of isEmpty, ie, if isEmpty is true, disabled is true and the user won't click the button unless the text input are filled. I tried some things, like change the return for another alternatives, or change the value of disable but i dont have good news.

I search from the web and this site, and the solutions doesn't resolve my problem.

Here i detach some code of the function, states and properties.

<View style={styles.submit}>
        <TouchableOpacity
          onPress={() => checkValidation()}
          disabled={emptyFields}
        >
          <Text style={styles.button}> Submit </Text>
        </TouchableOpacity>
      </View>

checkEmptyFields -> function call by checkValidation to determinate if the text inputs are empties

const checkEmptyFields = () => {
if (
  (id === "" && psw === "") ||
  (id === "" && psw !== "") ||
  (id !== "" && psw === "")
)
  setEmptyFields(true);

};

const checkValidation = () => {
checkEmptyFields();
verifyUser();
resetStates();

};

States used

const [id, setId] = useState("");

const [psw, setPsw] = useState("");

const [emptyFields, setEmptyFields] = useState(false);

CodePudding user response:

Use this way

const checkEmptyFields = () => {
if (!id || !psw) {
setEmptyFields(true)
}
};

CodePudding user response:

I found the problem. In the property disabled, i evaluate a state that ONLY calculates in a onPress function. The fix was to copy the line checkEmptyFields inside the disabled.

  • Related