Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 361
batisteo Avatar asked Nov 25 '19 08:11

batisteo


1 Answers

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>
like image 179
rixo Avatar answered Oct 11 '22 06:10

rixo