Home > Software engineering >  A conditional statement in Button
A conditional statement in Button

Time:06-15

I'm new to ReactJs, I have this button called "Add Item" that I would like to disable if a certain condition is reached. Basically I would to pass an if and else statement in the button. However I am stuck as to how to do it.

const [disable, setDisable] = useState(false);
var quantity = 11;

<Button
            if ( quantity > 10 ){ setDisable(true) } // don't know how to properly build here

            title="Add Item"
            buttonStyle={{backgroundColor: PrimaryColor, borderRadius: 10}}
            titleStyle={{fontSize:13}} 
            disabled={disable}   
            onPress={InsertItem}                     
          />

Any assist is kindly appreciated

CodePudding user response:

You probably don't want to have disabled stored as a state. If quantity is a prop or inside the state of your component, it's probably just sufficient to have a calculated value:

<Button disabled={quantity > 10} .... />

CodePudding user response:

  1. If you want to add any condition like this if ( quantity > 10 ){ setDisable(true) } then do it in onPress

  2. or you can useEffect with dependency variable so that it invokes every time there is any change in that variable

     React.useEffect(() => {
        if (quantity > 10) {
          setDisable(true)
        }
      }, [quantity])
  1. or simply just add a condition for disable in the disabled tag of Button like this disabled={quantity > 10} so whenever your quantity is greater than 10it will return true and it will be the same as disabled={true} and same goes for when the condition is false
    const [disable, setDisable] = useState(false);
    var quantity = 11;
    
       <Button
        title="Add Item"
        buttonStyle={{backgroundColor: PrimaryColor, borderRadius: 10}}
        titleStyle={{fontSize:13}} 
        disabled={quantity > 10}
        onPress={InsertItem}                     
       />
  • Related