23

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].

batisteo
  • 453
  • 1
  • 4
  • 10
  • 1
    found [this article](https://stacktuts.com/how-to-have-a-conditional-attribute-in-svelte-3) which can be helpful – Gangula Aug 09 '23 at 10:02

1 Answers1

50

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>
rixo
  • 23,815
  • 4
  • 63
  • 68
  • 3
    The `autofocus` in Svelte only works when it has no value - not even an empty string or true / false can be. How to solve it? What it comes from? – lukaszpolowczyk May 15 '21 at 19:31
  • `attributes are included unless their value is nullish (null or undefined).` is a really useful way to toggle attributes – Gangula Aug 09 '23 at 10:03