Additional Usage Examples

Here are a wide range of examples you might find useful for your component development.

Dynamic Class Names 

Attach styles dynamically to user interface elements based on varying conditions.

1<template>
2  <div class="{isActive && !isDisabled ? 'active' : 'inactive'}">
3    <span class="{`status-${getStatus().toLowerCase()}`}">{getStatus()}</span>
4  </div>
5</template>
1import { LightningElement } from "lwc";
2
3export default class DynamicClassComponent extends LightningElement {
4  isActive = true;
5  isDisabled = false;
6  status = "SUCCESS";
7
8  getStatus() {
9    return this.status;
10  }
11}

Conditional Rendering 

Show or don’t show user interface elements, depending on whether they’re relevant or not.

1<template>
2  <div>
3    {getUser() ? `Welcome, ${getUser().name}!` : 'Please log in'}
4  </div>
5  <div>
6    {isLoggedIn && user ? `Hello, ${user.name.toUpperCase()}!` : 'Guest'}
7  </div>
8</template>
1import { LightningElement } from "lwc";
2
3export default class ConditionalRenderingComponent extends LightningElement {
4  isLoggedIn = true;
5  user = { name: "John Doe" };
6
7  getUser() {
8    return this.isLoggedIn ? this.user : null;
9  }
10}

Data Formatting 

Store values in canonical data types (for example, timestamps) in your records for ease of programming, while still showing them in easy to understand formats.

1<template>
2  <div>
3    <p>Price: {formatCurrency(getPrice())}</p>
4    <p>Last updated: {formatDate(lastUpdated ?? Date.now())}</p>
5    <p>Items: {getItems().length > 0 ? `Found ${getItems().length} items` : 'None'}</p>
6  </div>
7</template>
1import { LightningElement } from "lwc";
2
3export default class DataFormattingComponent extends LightningElement {
4  basePrice = 99.99;
5  lastUpdated = Date.now();
6  allItems = ["item1", "item2", "item3"];
7
8  getPrice() {
9    return this.basePrice * 1.1; // Add 10% tax
10  }
11
12  getItems() {
13    return this.allItems.filter((item) => item);
14  }
15
16  formatCurrency(price) {
17    return `$${price.toFixed(2)}`;
18  }
19
20  formatDate(timestamp) {
21    return new Date(timestamp).toLocaleDateString();
22  }
23}

Complex Calculations 

1<template>
2  <div>
3    <p>Total: {calculateTotal()}</p>
4    <p>Discount: {getDiscount() > 0 ? `-${formatCurrency(getDiscount())}` : 'None'}</p>
5    <p>Final: {calculateTotal() - getDiscount()}</p>
6  </div>
7</template>
1import { LightningElement } from "lwc";
2
3export default class ComplexCalculationsComponent extends LightningElement {
4  subtotal = 100;
5  tax = 8.5;
6  shipping = 5.99;
7  discount = 10;
8
9  calculateTotal() {
10    return this.subtotal + this.tax + this.shipping;
11  }
12
13  getDiscount() {
14    return this.discount;
15  }
16
17  formatCurrency(amount) {
18    return `$${amount.toFixed(2)}`;
19  }
20}

Numeric Operations 

1<template>
2  <div>
3    <p>Binary: {0b1010}</p>
4    <p>Hex: {0xFF}</p>
5    <p>Octal: {0o777}</p>
6    <p>Power: {2 ** 8}</p>
7    <p>Bitwise: {flags & 0xFF}</p>
8  </div>
9</template>
1import { LightningElement } from "lwc";
2
3export default class NumericOperationsComponent extends LightningElement {
4  flags = 0b11111111;
5}

String Manipulation 

1<template>
2  <div>
3    <p>Full name: {[getFirstName(), getLastName()].join(' ')}</p>
4    <p>Uppercase: {getName().toUpperCase()}</p>
5    <p>Template: {`Hello ${getName()}, you have ${getCount()} items`}</p>
6  </div>
7</template>
1import { LightningElement } from "lwc";
2
3export default class StringManipulationComponent extends LightningElement {
4  firstName = "John";
5  lastName = "Doe";
6  name = "world";
7  count = 5;
8
9  getFirstName() {
10    return this.firstName;
11  }
12
13  getLastName() {
14    return this.lastName;
15  }
16
17  getName() {
18    return this.name;
19  }
20
21  getCount() {
22    return this.count;
23  }
24}

List Processing 

1<template>
2  <div>
3    <p>Total items: {getAllItems().length}</p>
4    <p>Active items: {getAllItems().filter(item => item.active).length}</p>
5    <p>
6      Average price: {getAllItems().reduce((sum, item) => sum + item.price, 0) /
7      getAllItems().length}
8    </p>
9  </div>
10</template>
1import { LightningElement } from "lwc";
2
3export default class ListProcessingComponent extends LightningElement {
4  allItems = [
5    { active: true, price: 10 },
6    { active: false, price: 20 },
7    { active: true, price: 30 },
8    { active: true, price: 15 },
9  ];
10
11  getAllItems() {
12    return this.allItems;
13  }
14}

Object and Array Operations 

1<template>
2  <div>
3    <p>Object: {({ name: 'John', age: 30 }).name}</p>
4    <p>Array: {getNumbers().join(', ')}</p>
5    <p>Computed: {getUser()['firstName']}</p>
6    <p>Nested: {getData()?.items?.[0]?.name ?? 'No items'}</p>
7  </div>
8</template>
1import { LightningElement } from "lwc";
2
3export default class ObjectArrayOperationsComponent extends LightningElement {
4  user = { firstName: "John" };
5  data = {
6    items: [{ name: "Item 1" }, { name: "Item 2" }],
7  };
8
9  getNumbers() {
10    return [1, 2, 3, 4, 5];
11  }
12
13  getUser() {
14    return this.user;
15  }
16
17  getData() {
18    return this.data;
19  }
20}

Event Handlers 

1<template>
2  <div>
3    <button onclick="{() => handleClick(getCount())}">Click me</button>
4    <button onclick="{() => incrementCount()}">Increment</button>
5    <button onclick="{() => updateField(getFieldValue())}">Update</button>
6  </div>
7</template>
1import { LightningElement } from "lwc";
2
3export default class EventHandlersComponent extends LightningElement {
4  count = 0;
5  fieldValue = "value";
6
7  getCount() {
8    return this.count;
9  }
10
11  getFieldValue() {
12    return this.fieldValue;
13  }
14
15  handleClick(count) {
16    alert("Button clicked with count:" + count);
17  }
18
19  incrementCount() {
20    this.count++;
21  }
22
23  updateField(value) {
24    alert("Field updated with:" + value);
25  }
26}

Type Checking 

1<template>
2  <div>
3    <p>Type: {typeof getValue()}</p>
4    <p>Is null: {getValue() === null}</p>
5    <p>Is undefined: {typeof getValue() === 'undefined'}</p>
6  </div>
7</template>
1import { LightningElement } from "lwc";
2
3export default class TypeCheckingComponent extends LightningElement {
4  value = "test";
5
6  getValue() {
7    return this.value;
8  }
9}