Sometimes we need to conditionally set an attribute in the Astro HTML markup.
Currently, in Astro version 4.0.0
and later, we can just set the attribute with a falsy value and no attribute will be set.
---type Props = { isDisabled?: boolean}
const { isDisabled = false } = Astro.props---
<button disabled={isDisabled}> Click me</button>
In former Astro versions, you will need to use undefined
. If not, Astro will set disabled="false"
and the browser will consider this attribute as truthy.
You can easily achieve this with a logical disjunction operator ||
.
---type Props = { isDisabled?: boolean}
const { isDisabled = false } = Astro.props---
<button disabled={isDisabled || undefined}> Click me</button>