What is the correct way to check if a certain condition is true or not when trying to set disabled state on a button ?
I have tried the code below, but I get an error.
Line 237:23: Unnecessary use of boolean literals in conditional expression no-unneeded-ternary
<Button
variant="contained"
className="global-button"
disableElevation
disabled={!brush_logs_list.length ? true : false}
onClick={applyForEntireMouth}>
APPLY FOR ENTIRE MOUTH
</Button>
CodePudding user response:
The answer from Bikas Lin is correct. Let me just expand a bit for clarity. The disabled flag only accepts boolean. When using .length to check, 0 (empty) will return false and anything else will return true. The ternary operator is therefore not needed at all because the .length returns exactly what you need.
There are multiple ways to go around this. Say there would be multiple possibilities, for example, if the .length exceeds given amount etc. In that case you want to define a function, for example "handleDisabled" and validate there. switch is a good way/option for these cases (no pun intended).
CodePudding user response:
Please try like this;
<Button
variant="contained"
className="global-button"
disableElevation
// disabled={!brush_logs_list.length ? true : false}
disabled={!brush_logs_list.length} // instead of above line
onClick={applyForEntireMouth}
>
APPLY FOR ENTIRE MOUTH
</Button>
Actually, the type of !brush_logs_list.length
is already boolean
, so you don't need to ? :
operator. Just using !brush_logs_list.length
is enough.
CodePudding user response:
Use disabled={!!!brush_logs_list.length}
CodePudding user response:
You can try like this
<Button
variant="contained"
className="global-button"
disableElevation
disabled={(brush_logs_list || []).length}
onClick={applyForEntireMouth}>
APPLY FOR ENTIRE MOUTH
</Button>