atlassian-labs / compiled

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

Styles are lost after composing styled component and then using `as` prop #1644

Open ajayjindal2 opened 6 months ago

ajayjindal2 commented 6 months ago

Describe the bug

If i have styled component from @compiled/react like H3, and then reuse it to be styled again into Heading and then use as prop to render it as h1.

const H3 = styled.h3({
  fontSize: '1.5rem',
  lineHeight: '30px',
  fontWeight: '600',
});

const Heading = styled(H3)({
  marginBlock: '0 5px',
});

const SearchHeading = () => (
  <Heading as="h1">
         Search results
  </Heading>
);

i would only get styles of marginBlock: '0 5px', in UI rendering the styles from H3 are lost

image

Expected behavior

styles from H3 are should also be applied.

Workaround

Using as props before 2nd styled on the component as suggested by @liamqma +++++

const H3 = styled.h3({
  fontSize: '1.5rem',
  lineHeight: '30px',
  fontWeight: '600',
});

const H1 = (props) => <H3 as="h1" {...props} />;

const Heading = styled(H1)({
  marginBlock: '0 5px',
});

const SearchHeading = () => (
  <Heading>
         Search results
  </Heading>
);
image
liamqma commented 6 months ago

To add more context:

const Heading = styled(H3)({
  marginBlock: '0 5px',
});

gets compiled to

const Heading = forwardRef(
  ({ as: C = H3, style: __cmpls, ...__cmplp }, __cmplr) => {
    return (
      <CC>
        <CS>{[_]}</CS>
        <C
          {...__cmplp}
          style={__cmpls}
          ref={__cmplr}
          className={ax(["_1mou1s5a", __cmplp.className])}
        />
      </CC>
    );
  }
);

As you can see, as overwrites H3. I would recommend using css prop instead of styled. https://compiledcssinjs.com/docs/api-css