0

Pretend I have an element that I wish to give a literal class, such as:

<p class="slds-text-title">My Title</p>

But I also have a dynamically determined class I wish to add, which I would normally do as:

<p class={dynamicClassVariable}>My Title</p>

Is there a way to add both to a single element in the HTML? The following is invalid:

<p class="slds-text-title {dynamicClassVariable}">My Title</p>

The only other way I can think of is to move my literal class name to the JavaScript and append it to the dynamic value, but I would rather not have to move all literal class names to the JavaScript every time I have a dynamic style to apply.

0

in order to do this, you should use a getter in your JS:

HTML:

<p class={dynamicStyleClassP} >Some text</p>

JS:

get dynamicStyleClassP(){
    let css = 'slds-text-title';
    if( somecondition ){
      css += ' someDynamicClass';
    }
    return css;
}

using the getter will remain reactive on your UI and when rendering changes due to other reactive changes, it will update your css with the dynamic classes that you need/desire to add.

1
  • This does not answer the question which specifically requests an alternative to this approach. Moving class literals to the JavaScript mixes responsibilities: JavaScript is no longer just for dynamic cases, and it becomes impossible to consistently apply the same styles without moving all class literals to JavaScript. – Nathan Fig Apr 2 '20 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.