batisteo
batisteo

Reputation: 497

How to have a conditional attribute in Svelte 3?

Is there a simpler way to write the following checkbox component:

<script>
  export let disabled = false;
</script>

{#if disabled}
  <label class="checkbox" disabled>
    <input type="checkbox" {disabled} />
    <slot></slot>
  </label>
{:else}
  <label class="checkbox">
    <input type="checkbox" {disabled} />
    <slot></slot>
  </label>
{/if}

Having <label disabled="false"> is not acceptable because Bulma have a CSS class .checkbox[disabled].

Upvotes: 27

Views: 20264

Answers (1)

rixo
rixo

Reputation: 25001

disabled || null (or disabled || undefined) will do the trick:

<label class="checkbox" disabled={disabled || null}>
  <input type="checkbox" {disabled} />
  <slot></slot>
</label>

From the docs:

... [A]ttributes are included unless their value is nullish (null or undefined).

<input required={false} placeholder="This input field is not required">
<div title={null}>This div has no title attribute</div>

Upvotes: 58

Related Questions