styled-components / xstyled

A utility-first CSS-in-JS framework built for React. 💅👩‍🎤⚡️
https://xstyled.dev
MIT License
2.28k stars 105 forks source link

Using "tx" in literals #245

Closed XenTerSeO closed 3 years ago

XenTerSeO commented 3 years ago

When using the "tx" utility in the "box-shadow" property, a problem arose:

const Hello = styled.div`
  box-shadow: ${(p) => (p.test ? `0 2px 6px 2px ${th.color('example')}` : 'none')};
`

— it won't work.

const Hello = styled.div`
  box-shadow: ${(p) => (p.test ? th.color('example') : 'none')};
`

— outside of the literal it will work, but it is not what want.

What is the best way to use "tx" in this case?

agriffis commented 3 years ago

The main problem is that you need to pass props to the th function. This happens automatically if it's interpolated into the tagged template literal, but not if you embed it in a simple template literal.

So you can make a small change to your code:

const Hello = styled.div`
  box-shadow: ${p => p.test ? `0 2px 6px 2px ${th.color('example')(p)}` : 'none'};
`

but here are some better options with the css tagged template literal:

const Hello = styled.div`
  box-shadow: ${p => p.test ? css`0 2px 6px 2px ${th.color('example')}` : 'none'};
`

const Hello = styled.div`
  ${p => p.test && css`box-shadow: 0 2px 6px 2px ${th.color('example')};`}
`

const Hello = styled.div(p => p.test && css`
  box-shadow: 0 2px 6px 2px ${th.color('example')};
`)

At least I think the last one works. You'll have to test it.

You might also be interested in https://xstyled.dev/docs/box-shadow/