#Why does useStylesScoped$ add the "scoping css class" to all the children?

10 messages · Page 1 of 1 (latest)

silk mortar
#

If I take this component (from the tutorial, with small changes):

export const ComponentA = component$(() => {
  useStylesScoped$(`
    .component {
      background-color: red;
    }`);
  return (
    <div class="component">
      <div>A</div>
      <div>
        b
        <div>
          C
          <div>D</div>
        </div>
      </div>
      <p>e</p>
    </div>
  );
});

It generates what we see in the image. below, in the DOM. Is there any reason to repeat the scoping css class on all the child nodes (even on the deeply nested ones)? It seems we could save a few bytes by not doing that and still have the styles correctly applied.

👇

haughty igloo
#

I'm going to guess that it's the safest way to implement it if you don't parse the css. Parsing the css takes time and JS

silk mortar
#

Performance is a good reason

#

But it seems that we have a performance reduction here by having to recursively iterate over all the inner nodes during the compilation process 🤷‍♂️

#

Probably saves time in more complex scenarios where you're scoping more style rules that may affect elements of the nested tree

haughty igloo
#

right. I don't like useStylesScoped$ at all

silk mortar
#

I can see that if you apply a css class name to an inner element, it'll keep the same scoping identifier. It seems like a design choice to add the scoping identifier in the first iteration and further styles afterwards:

export const ComponentA = component$(() => {
  useStylesScoped$(`
    .component {
      background-color: red;
    }
    .component .my-component {
        color: blue;
    }`);
  return (
    <div class="component">
      <div>A</div>
      <div>
        b
        <div class="my-component">
          C
          <div>D</div>
        </div>
      </div>
      <p>e</p>
    </div>
  );
});
#

In more complex scenarios where you're nesting components that have scoped styles with the same name, this will prevent the parent component from leaking the styles to the child component

haughty igloo
#

the better solution is to create scoped css in the first place (e.g. put in a file called .module.css) and use useStyles$