Search code examples
reactjsemotion

Nesting Emotion 10 classes for cascade


Previously in Emotion 9 you were able to use Emotion class names to take advantage of cascade. You would wrap the emotion const in curly brackets and prefix it with a period, and then dollar sign. For example, you could do this:

const child = css`
  color: green;
`;
const parent = css`
  color: red;
  .${child} {
    color: yellow;
  }
`;

<div className={parent}>I am red</div>
<div className={child}>I am green</div>
<div className={parent}>
  <div className={child}>I am yellow</div>
</div>

How can I go about achieving this behavior in Emotion 10? That is my question.

The following is further information about what happens when you don't use a period-dollar sign.


Now, the following was and is desirable: if no period are used in Emotion 9 or 10, the parent const will inherit the nested const styles. And furthermore, if that nested const then has overriding styles, those would ultimately be inherited by the parent.

const child = css`
  color: green;
`;
const parent = css`
  color: red;
`;
<div className={parent}>I am red</div>
<div className={child}>I am green</div>

const child = css`
  color: green;
`;
const parent = css`
  ${child}
`;
<div className={parent}>I am green</div>

const child = css`
  color: green;
`;
const parent = css`
  ${child} {
    color: yellow;
  }
`;
<div className={parent}>I am yellow</div>

const child = css`
  color: green;
`;
const parent = css`
  color: red;
  ${child}
`;
<div className={parent}>I am green</div>

const child = css`
  color: green;
`;
const parent = css`
  color: red;
  ${child} {
    color: yellow;
  }
`;
<div className={parent}>I am yellow</div>

Solution

  • The following will work, it just doesn't work in CodePen as the output code there has more text tacked onto it, and it hashes the const names all over again. But if you test in your own code base, this does work. I don't like doing it, stepping into the object to get the name in there, it feels hacky. Would like Emotion to have something specific for these instances.

    const cat = css`
      color: red;
    `;
    const dog = css`
      color: green;
      .css-${cat.name} {
        border-bottom: 1px solid currentColor;
      }
    `;