Skip to main content

Sample web component analysis

Let's analyse the sample widget from our project:

import { LitElement, html, unsafeCSS } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import styles from "./acuitas-design-system.css?inline";

@customElement('sample-widget')
export class SampleWidget extends LitElement {
@property()
imageId: string = '';

@property({ type: Boolean })
isModalOpen: boolean = false;

@property({ type: Object })
additionalProps: Record<string, any> = {};

render() {
return html`
<div>
<h2 class="header">Sample Widget</h2>

${!this.isModalOpen ? html`
<button class="btn-primary" @click=${this._openModal}>
Open in Full Screen Modal
</button>
` : html`
<button class="btn-primary" @click=${this._closeModal}>
Close Modal
</button>
`}

${this.imageId ? html`
<div class="section">
<p><strong>Image identifier:</strong> ${this.imageId}</p>
</div>
` : ''}
</div>
`;
}

private _openModal() {
this.dispatchEvent(new CustomEvent('open-modal', {
bubbles: true,
composed: true
}));
}

private _closeModal() {
this.dispatchEvent(new CustomEvent('close-modal', {
bubbles: true,
composed: true
}));
}

static styles = unsafeCSS(styles);
}

Key features demonstrated

The sample widget demonstrates several important web component concepts:

  • Lit Framework use: Shows how to use Lit decorators and template system for reactive components.
  • Properties: Demonstrates reactive properties with proper type definitions for component configuration.
  • Event handling: Uses custom events for parent-child communication following web component patterns.
  • Conditional rendering: Shows dynamic template rendering based on component state.
  • CSS integration: Demonstrates how to integrate external stylesheets with proper encapsulation.
  • TypeScript: Provides full type safety throughout the component implementation.

Architecture patterns

The component follows several web component best practices:

  • Property-driven architecture: Component behaviour is controlled through declarative properties.
  • Event-based communication: Uses standard custom events to communicate with parent elements.
  • Encapsulated styling: Styles are scoped to the component using Shadow DOM.
  • Declarative templates: Uses HTML-based templates with data binding for maintainable code.