MambaForever
MambaForever

Reputation: 367

Conditional Logic Inside of Components

Here I have this checkbox which appears inside of the "Rate" field, when the Bid is in draft or pending status, this checkbox should appear, when it is not, it should disappear. For some reason I can't figure out how to structure this conditional logic and its only taking in the second argument so when the item is in "Draft" status, the checkbox is not showing up. What am I doing wrong here:

 <HrCurrencyInput
            name='Rate'
            label='Rate'
            width={width.medium}
            onChange={handleChange}
            value={formik.values.OverrideRate ? formik.values.Rate : selectedBillable?.Cost ?? ''}
            errors={formik.errors.Rate}
            InputProps={{
                endAdornment: 
                (
                  status === "Draft" || status === "Pending" &&
                  (
                    <InputAdornment position="end">
                        <HrCheckBox
                            name="OverrideRate"
                            checked={formik.values.OverrideRate}
                            onChange={handleOverrideChange}
                            sx={{
                                m: "0 -8px 0 0",
                                "& .MuiCheckbox-root": {
                                    p: 0
                                }
                            }}
                        />
                    </InputAdornment>
                    )
                )
            }}
            InputLabelProps={{ shrink: true }}
            disabled={!formik.values.OverrideRate}
        />

Pending: Pending status

Draft: Draft Status

Upvotes: 0

Views: 60

Answers (1)

Kavian Rabbani
Kavian Rabbani

Reputation: 984

The thing to be aware of is that booleans are valid react elements too. If you render try to render false or true React will ignore them. Here, if your first condition is truthy, it evaluates to true and the browser will not even bother checking other conditions (since it's followed by ||).
Basically when you have a condition like this:

A || B

If A is truthy, it will be evaluated and B is not even taken into account. It's the same in your example. If the status is "draft", the value of endAdornment would be:

true || ... && ...

which is === true.

Trying to group your first two conditions here like:

(status === "Draft" || status === "Pending") && ...

would fix the problem as it the first parentheses evaluates to true or false.
In && cases then, if the first operand is false, it evaluates to false (nothing renders in result for you). And if it evaluates to true, it goes to the next step and renders what you want. The rendered thing is an object and is truthy. So the final evaluated expression of your condition would be the exact rendered object and you're done.

Please let me know if I need to clarify more.

Upvotes: 2

Related Questions