Add the #DF24 Developer Keynote to your agenda. Join us in-person on 9/19 at 2:30 p.m. PT or on Salesforce+ at 5 p.m. PT for the must-see session built just for developers.

Bind HTML Classes

AVAILABLE API VERSIONS
Available in LWC API v62.0 and later

Manipulate a component or an element's class list easily using its class attribute. You can use class object binding instead of string concatenation to generate complex class names.

Here's an example that evaluates multiple classes on an element.

Pass in your class object to the getter.

Your element renders like this.

In LWC API v62.0 and later, use an array or an object to bind multiple styles to an element's class attribute.

  • An array is evaluated based on its individual items based on class object binding semantics. For example, if you pass in ["highlight", "yellow"], the element renders class="highlight yellow".
  • An object is evaluated based on class object binding semantics. LWC iterates over the enumerable string properties on the object, excluding symbols and properties on the proto-chain. It applies the classes with the keys associated with a truthy value. For example, if you pass in { highlight: true, hidden: false }, the element renders class="highlight".

In LWC API v62.0 and later, booleans, numbers, and functions are removed instead of converted to a string. For example, if you pass in true, false, or 10, the element renders class="". LWC ignores all other values, like primitive and complex objects.

To render a boolean or numerical value as a string, such as class="false" or class="1", convert the value to a string using String(value).

Before LWC API v62.0(equivalent to LWC OSS v7.0.0), the class attribute rendered booleans, numbers, functions, arrays, and objects differently. See LWC v7.0.0: Class object binding.

These examples show the differences between LWC API v62.0 and previous versions.

TypeExampleOutput in LWC API v62.0Output in LWC API v61.0
String"note highlight"class="note highlight"class="note highlight"
Booleanfalseclass=""class="false"
Number10class=""class="10"
Function() => {}class=""class="() => {}"
Array["note", "highlight"]class="note highlight"class="note,highlight"
[false, 'note', null]class="note"class="false,note,"
['block', { note: true }, ['highlight']]class="block note highlight"class="block,[object Object],highlight"
Object{block: true, hidden: false, 'note highlight': true }class="block note highlight"class="[object Object]"

See Also