atlassian-labs / compiled

A familiar and performant compile time CSS-in-JS library for React.
https://compiledcssinjs.com
Apache License 2.0
1.99k stars 68 forks source link

Nested selectors and compiled CSS #1518

Open yamadapc opened 1 year ago

yamadapc commented 1 year ago

What is the idiomatic approach for the following types of use-cases?

Let's say I have:

<Button>
   <Icon>Icon</Icon>

   Text
</Button>

And I would want Icon to be red on hover over "Button".

This is what I'd write in CSS:

.Button:hover .Icon {
    ...
}

How would you write this with compiled?

dddlr commented 1 year ago

Hmm that's a good question - we recommend using JS to detect the hover on Button and store this in a variable, and then pass the variable value as a prop to the Icon.

To give some reasons for why we suggest this: this is a performance compromise 😅, since even though using JS (as opposed to a pure CSS solution) does incur an extra cost...

I made a quick React example below - I'm not the best with React so the onMouseEnter/onMouseLeave could probably be optimised a bit:

const Button = styled.div({ fontSize: '25px' });
const Icon = styled.div({
    color: (prop) => prop.isHover ? 'red' : 'black',
});

const Component = () => {
  const [isHover, setIsHover] = React.useState(false);
  return <>
    <Button onMouseEnter={() => setIsHover(true)} onMouseLeave={() => setIsHover(false)}>
      <Icon isHover={isHover}>hello world</Icon>
    </Button>
  </>;
}

If you're doing something inside JFE, we recommend asking DST to see if there's any atlaskit primitives or packages suitable for the kind of button that you're creating (or migrating)