0

There are two ways for dynamic styling in LWC -

  1. CSS class binding like <div class={styleClass}> with getter.

  2. Handle classList in the target element with querySelector().

    Is there any guideline or best practice for which to use?

1 Answer 1

0

The getter method has the advantage of remembering the state when a component is hidden/shown (e.g. via if:true or if:false), while the DOM-manipulation method can't. On the other hand, using DOM-manipulation likely has better performance characteristics in larger components. I'm not sure there's a solid recommendation either way, but I would suggest that you choose one method and use it consistently.

3
  • I would add that when you use the DOM manipulation method, you're limited to static styles that have been pre-defined in CSS. If you want to handle use cases like "the background color should be configurable in Lightning App Builder", I think you have to use inline CSS. Dec 10, 2019 at 18:54
  • @MatthewSouther That's a good point. I had a feeling I was missing something.
    – sfdcfox
    Dec 10, 2019 at 19:10
  • Thank you sfdcfox and Matthew!! Makes sense.
    – segway13
    Dec 12, 2019 at 6:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .