Reputation: 89
I am trying to disable a button depending on a couple of conditions.
<Button disabled={((myobject && myobject.name === "bob") || user.registered) ? true : false} >my button</Button>
Essentially, I want to disable the button if myobject.name
is "bob" or if the user is registered (eg. user.registered is not nil). As it stands now, the button seems to get disabled if myobject.name
is "bob" but it seems to ignore user.registered
. What am I doing wrong?
many thanks!
Upvotes: 0
Views: 78
Reputation: 1
It looks like you're probably pretty close, the code you have should work fine. I would make sure to check two things. Make sure that user.registered has a "truthy" value.
If it's a string or a number it could be evaluating to false where you don't expect it. In Javascript 0
undefined
null
""
(empty string) and NaN
are all evaluated as false
You should also make sure that myobject is defined somewhere. You'll still get a reference error if myobject never gets declared. if myobject is any of those values that evaluate to false though and user.registered == true
then your code should do what I think you're trying to accomplish. If not you might need to give a little more detail as to what you expect to happen and some sample values to look at.
Upvotes: 0
Reputation: 48
Inside the button tag you could try to use just the two constraints you want to impose (I didn't understand why the myobject at the beginning though). It could be something like the following:
(myobject.name === "bob" || user.registered) ? true : false
Upvotes: 0
Reputation: 10873
You can simplify your code with optional chaining and by omitting the ternary, as it is redundant here:
<Button disabled={myobject?.name === "bob" || user.registered}>my button</Button>
Upvotes: 4