ben-rogerson / twin.macro

🦹‍♂️ Twin blends the magic of Tailwind with the flexibility of css-in-js (emotion, styled-components, solid-styled-components, stitches and goober) at build time.
MIT License
7.9k stars 184 forks source link

Is there a way to use variables for colour names with emotionjs + twin? #63

Closed theairbend3r closed 4 years ago

theairbend3r commented 4 years ago

I have an array which contains key-value pairs as follows -

const colourTypeMapping = [
  { type: "normal", color: "bg-orange-700" },
    .
    .
    .
]

Now, I want to create a <div> </div> which has some base styles but it uses the bg-color from the above colourTypeMapping array.

For instance,

const StyledDiv = (props) => {
    const {objType} = props
    // search for the type in `colourTypeMapping` and save in the variable `col` below
    const objFound = colourTypeMapping.find(obj => obj.type === objType)
    const col = objFound.color

    return (
    )
}

How do I complete the above component?

rbutera commented 4 years ago

Please see issue #17

rbutera commented 4 years ago

For reference - you can see this approach

export const PrimaryButton = styled(Button)`
  ${({ color }) =>  color === 'blue' ?  tw`hover:border-blue-400` : tw`hover:border-gray-400`};
`;

or you could do something like this

const generateBorderColor = (color) {
 switch(color) { 
      case 'blue': 
           return tw`hover:border-blue-400`
      default:
           return tw`hover:border-gray-400`
    }
} 

const PrimaryButton = styled(Button)`
   ${({color}) => ${generateBorderColor(color}}}
`