From LWC API v62.0 you can bind element classes using the class attribute with arrays or objects. This simplifies dynamic class toggling and keeps templates clean.
Overview
Starting in Lightning Web Components API version 62.0, LWC supports binding the HTML class attribute to complex values such as arrays or objects. Instead of concatenating strings in JavaScript and returning a space-delimited string, you can return an array of class names or an object where keys are class names and values are booleans. The framework will render this as a space-separated list of classes.
Why this matters
This feature makes dynamic styling more maintainable and readable. It reduces string-building bugs and keeps template markup concise. It is especially useful when multiple conditional classes must be applied based on component state.
Example
Below is a minimal LWC example showing a getter that returns an object and an array for class binding. The template uses the class attribute with the property.
// myComponent.html <template> <div class={containerClass}> Dynamic classes applied here </div> <button onclick={toggleActive}>Toggle Active</button> </template> // myComponent.js import { LightningElement, track } from 'lwc'; export default class MyComponent extends LightningElement { @track isActive = false; get containerClass() { // Return an object return { 'slds-box': true, 'is-active': this.isActive, 'custom-highlight': !this.isActive }; // Or return an array: // return ['slds-box', this.isActive ? 'is-active' : 'custom-highlight']; } toggleActive() { this.isActive = !this.isActive; } }
Best practices
- Prefer objects for many conditional classes — keys are explicit and boolean values are clear.
- Use arrays when you want to include computed or variable class names without explicit keys.
- Keep class names consistent with SLDS when styling Salesforce UI components.
- Test in different API versions; this feature requires LWC API >= 62.0.
Use cases
Dynamic forms, responsive UI elements, state-based highlighting, and conditional layout adjustments are common scenarios that get simpler with class binding.
Conclusion
Class binding in LWC simplifies conditional styling and improves maintainability. For Salesforce admins and developers, it reduces template complexity and minimizes runtime string manipulation bugs.
Why this matters: clear, declarative styling helps teams ship UI faster and with fewer regressions — especially in larger components where many state-driven classes must be managed.
Leave a Reply