Search code examples
javascriptreactjsreact-nativeconditional-operator

Multiple Conditons in ternary operator React Native


Hello Guys I have two conditions working with the ternary operator in javascript.

Here is my code it basically tells a button to be disabled or enabled:

disabled={(props.isAllowedState && (props.zkub == " " || props.zkub == "B")) || (!props.zkub == " " || !props.zkub == "B") ? false : true}

I also tried it this way:

disabled={(props.isAllowedState && (props.zkub == " " || props.zkub == "B")) ? false : (!props.zkub == " " || !props.zkub == "B") ? false : true}

But it does not work, when I take the conditions seperatly and test both of them it works but together they dont.

Maybe someone can give me a hint on how to solve this.

Faded

Edit: My If approach

  const checkDisableButton = () => {                                                 
    if(props.isAllowedState && (props.zkub == " " || props.zkub == "B")) {
      return false 
    } if (!props.zkub == " " || !props.zkub == "B") {
      return false
    } else {
      return true
    }
  };

The call:

disabled={() => checkDisableButton()}

Solution

  • I would create an isDisabled function that uses an if statement rather than a complicated ternary.

    function isDisabled() {
    
      const { isAllowedState, zkub } = props;
    
      if (isAllowedState && (zkub === ' ' || zkub === 'B')) return false;
      if (zkub !== ' ' || zkub !== 'B') return false;
      return true;
    
    }
    

    Then call it:

    disabled={isDisabled()}