propConverters

Table of Contents

Description

The propConverters module provides Lit Element property converters for handling boolean attributes in web components. These converters manage the conversion between JavaScript boolean values and HTML attribute strings.

Basic Usage

Import and use the converters in your Lit Element component properties:

import { boolTrueFalse, boolExists } from './utils/propConverters.js';

static properties = {
enabled: { type: Boolean, reflect: true, converter: boolTrueFalse },
visible: { type: Boolean, reflect: true, converter: boolExists }
};

boolTrueFalse

Converts between boolean values and explicit "true"/"false" string attributes.

Behavior

HTML Usage

<my-component enabled="true"></my-component>
<my-component enabled="false"></my-component>

boolExists

Converts between boolean values and attribute presence/absence.

Behavior

HTML Usage

<my-component visible></my-component>        <!-- visible = true -->
<my-component></my-component> <!-- visible = false -->

Examples

Component with Both Converters

import { LitElement, html } from 'lit';
import { boolTrueFalse, boolExists } from './utils/propConverters.js';

class MyComponent extends LitElement {
static properties = {
autoplay: { type: Boolean, reflect: true, converter: boolTrueFalse },
hidden: { type: Boolean, reflect: true, converter: boolExists },
loop: { type: Boolean, reflect: true, converter: boolTrueFalse }
};

constructor() {
super();
this.autoplay = false;
this.hidden = false;
this.loop = false;
}

render() {
return html`
<div ?hidden="
${this.hidden}">
Content
${this.autoplay ? 'with' : 'without'} autoplay
${this.loop ? '(looping)' : ''}
</div>
`
;
}
}

HTML Usage Examples

<!-- Using boolTrueFalse converter -->
<my-component autoplay="true" loop="false"></my-component>

<!-- Using boolExists converter -->
<my-component hidden></my-component>

<!-- Combined usage -->
<my-component autoplay="true" loop="true" hidden></my-component>

When to Use Each Converter

Use boolTrueFalse when:

Use boolExists when: