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:
If you want to add any condition like this
if ( quantity > 10 ){ setDisable(true) }
then do it in onPressor 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])
- or simply just add a condition for disable in the
disabled
tag ofButton
like thisdisabled={quantity > 10}
so whenever your quantity is greater than 10it will return true and it will be the same asdisabled={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}
/>