MathiasGilson / Tailwind-Styled-Component

Create Tailwind CSS React components like styled components with class names on multiple lines and conditional class rendering
MIT License
818 stars 43 forks source link

Adapting based on props #59

Closed fernandame closed 2 years ago

fernandame commented 2 years ago

On styled-components' original docs, there's a way that we can pass a function to the styled component's template literal and adapt the primary state based on its props:

const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.primary ? "palevioletred" : "white"};
`;

Since tailwind CSS doesn't support interpolations, i.e. bg-{color}, the exact code above can't work for tailwind-styled-components. But perhaps we can have this functionality here as well. I thought the following syntax should work:

const Button = tw.button`
  bg: ${props => props.primary ? "red-500" : "white"};`;
  text: ${props => props.primary ? "white" : "red-500"};`;

And then identify the properties mentioned, so it becomes something like

{props.primary ? 'bg-red-500 text-white' : 'bg-white text-red-500'}

Is there a way it could be done?

randallmlough commented 2 years ago

Yeah you can do that. He's a snippet where I use a switch case for button sizing variants


export const StyledButton = tw.button`
  text-red-500
  ${ p => {
      switch ( p.$size) {
        case 'sm':
          return 'py-1 px-2 text-xs font-normal h-8'
        case 'md':
        case 'base':
          return 'py-2 px-4 text-sm font-normal h-10'
        case 'lg':
          return 'py-4 px-4 text-base font-normal h-14'
        case 'xl':
          return 'py-4 px-4 text-xl font-normal'
      }
    }}
`
fernandame commented 2 years ago

@randallmlough I did that as well, but it's not really the same as the original, is it? Nice workaround, though

randallmlough commented 2 years ago

Oh I see the nuance of your question now. What you are asking for is more of a limitation with Tailwind than this library. Tailwind's purging mechanism cant handle things like text-${DYNAMIC_COLOR}-500 which is essentially what you are wanting