EDIT: Actually I was wrong, the first example also doesn't work! It also interpolates the code!!


I'm experimenting with styled-components css prop api and I ran into the following problem:

This code works well:

const myCss = css<PropsWithTheme>`
  width: 100px;
  height: 100px;
  color: ${props => props.theme.color};
`

const MyComponent = () => <div css={myCss.toString()} />

But the following does not:

const getCss = (color: strinbg) => css<PropsWithTheme>`
  width: 100px;
  height: 100px;
  color: ${color}; // I tried injecting the color directly
  color: ${() => color}; // And also returning it from a callback inside the css``, just as I would access props/theme
`

const MyComponent = () => <div css={getCss('red').toString()} />

The output css here is width: 100px; height: 100px; color: ,red,; ,() => color,;, which is obviously not valid.

Using template string interpolation to stringify the output solves the problem, but results in very bad readability due to Prettier enforcing this format:

const MyComponent = () => (
  <div
    css={`
      ${getCss('red')}
    `}
  />
)

Unfortunately moving the inerpolation anywhere outside the css prop definition ( in component body or creating a stringify function) breaks the functionality (either prop/theme access, all css doesn't get applied at all).

It seems to be related to this issue: https://github.com/styled-components/styled-components/issues/1641, but the suggested solution there is to use the css helper function, which I'm already doing :(

Is there an easy fix to my problem?

0

There are 0 best solutions below