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.

1 Answer 1

1

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.

Update:

I can also see possibly two other alternatives. One still leverages the above, but does not move the literal classes to the JS.

Approach 1: (Slight risk of collision with CSS styling)

p[data-whatever="something"] {
  ...
}

The above would apply the dynamic parts of your style based on data attributes, not necessarily applying other classes, but enabling you to apply the certain aspect that you wish on the fly without JS. Not tested, but supported in CSS.

Approach 2:

<p class="literal-class-names">
  <span class={dynamicClassesFromJS}>
      ...your content
  </span>
</p>

wrapping your content in a span and only conditionally setting classes from JS, or setting nothing in here at all would be safe as well and not cause other behavior from the native html layout elements.

2
  • 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. Commented Apr 2, 2020 at 13:23
  • @NathanFig could maybe try using an alternative in the CSS stylesheet, haven't checked if supported yet in LWC - but potentially leverage data attributes. e.g. div[data-var="1"] { ...styles } but when combining with other class literals, I can imagine there is risk for CSS conflicts Commented Jan 20, 2024 at 15:33

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.