Reputation: 130
I am trying to add a custom button built by MUI to my project. I want to enable my button if 2 objects are not empty, otherwise the button remains disabled. I have written code that is working half correctly.
I want to only enable my button if 2 condition satisfies. But the button becomes enabled only when one condition meets the criteria. The ternary operation is not accepting the && condition.
How can I tackle this problem?
{Object.keys(userSelectDevicename).length === 0 && Object.keys(userSelectDevicecategory).length === 0 ? (
<>
{" "}
<WsButton type="submit" size="small" variant="contained" disabled={bool}>
Add
</WsButton>
</>
) : (
<>
{" "}
<WsButton type="submit" size="small" variant="contained" disabled={!bool}>
Add
</WsButton>
</>
)};
Upvotes: 1
Views: 585
Reputation: 9344
You have two identical JSX in each case. The changing factor is disabled={!bool}
. You can use ternary operator for this, but I would do something different, like below. To make the code cleaner. Which is to create a function that returns the disabled boolean state of the button.
export default function YourComponent(){
function getBool(){
let lengthOne = Object.keys(userSelectDevicename).length
let lenghtTwo = Object.keys(userSelectDevicecategory).length
if(lengthOne === 0 && lengthTwo === 0) return true
else return false
}
return(
<>
{" "}
<WsButton type="submit" size="small" variant="contained" disabled={!getBool()}>
Add
</WsButton>
</>
)
}
Upvotes: 1
Reputation: 965
Add both conditions inside small brackets. &&
works as a conditional operator first and will only check the Object.keys(userSelectDevicename).length === 0
first only if its true based on it. It will run the 2nd half. That is the code from Object.keys(userSelectDevicecategory).length === 0) ? ....
when adding the brackets brackets priority will be more and the condition will be evaluated as a whole and then the ternary operator will kick in based on result of the conditions.
{(Object.keys(userSelectDevicename).length === 0 && Object.keys(userSelectDevicecategory).length === 0) ? (
<>
{" "}
<WsButton type="submit" size="small" variant="contained" disabled={bool}>
Add
</WsButton>
</>
) : (
<>
{" "}
<WsButton type="submit" size="small" variant="contained" disabled={!bool}>
Add
</WsButton>
</>
)}
Upvotes: 1