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.
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 }
};
Converts between boolean values and explicit "true"/"false" string attributes.
<my-component enabled="true"></my-component>
<my-component enabled="false"></my-component>
Converts between boolean values and attribute presence/absence.
<my-component visible></my-component> <!-- visible = true -->
<my-component></my-component> <!-- visible = false -->
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>
`;
}
}
<!-- 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>
Use boolTrueFalse when:
Use boolExists when: