Home > Mobile >  React Js if-else build up
React Js if-else build up

Time:06-15

I'm new to Reactjs. I'm currently learning how to build an if else statement but can't seem to properly do it.

{voucherDetails.target_shop_name_validation ? (

          if ( A > 5 ) {
          setDisabled(true);}  // not sure how to properly build if here
          

          ) :

          <Button

            title="SEE NEARBY SHOP"
            buttonStyle={{backgroundColor: PrimaryColor, borderRadius: 10}}
            titleStyle={{fontSize:13}} 
            disabled={isDisabled}   
            onPress={NearByShop}                     
          />
        
          }

CodePudding user response:

Normally, I you would try this for an if else

{x ? y : a}

But in your case I see an outer if statement and an if and else inside of it, so I dont think this would work. However the following should.

{(() => {
    if (voucherDetails.target_shop_name_validation){
        if ( A > 5 ) {
            setDisabled(true);
        }  // not sure how to properly build if here
        else {
            return (
                <Button

                title="SEE NEARBY SHOP"
                buttonStyle={{backgroundColor: PrimaryColor, borderRadius: 10}}
                titleStyle={{fontSize:13}} 
                disabled={isDisabled}   
                onPress={NearByShop}                     
                />
            )
    }
})()}

CodePudding user response:

Another approach would be doing something like this:

{voucherDetails.target_shop_name_validation
  ? (
    (A > 5) && setDisabled(true)
  ) : (
    <Button
      title = "SEE NEARBY SHOP"
      buttonStyle={{
        backgroundColor: PrimaryColor,
        borderRadius: 10
      }}
      titleStyle={{ fontSize: 13 }}
      disabled={isDisabled}
      onPress={NearByShop}
    />
  )
}

However this logic seems a bit weird since you are setting disabled to true in the if statement, and in the else statement you use the value of isDisabled, which would never render the value true you set above.

Maybe a better approach would be to check for (A > 5) and then setDisabled(true) before you render your component, and then you can change your code to:

{!voucherDetails.target_shop_name_validation &&
  (
    <Button
      title = "SEE NEARBY SHOP"
      buttonStyle={{
        backgroundColor: PrimaryColor,
        borderRadius: 10
      }}
      titleStyle={{ fontSize: 13 }}
      disabled={isDisabled}
      onPress={NearByShop}
    />
  )
}
  • Related