Search code examples
react-nativestyled-components

How can I use a switch case inside attrs of a component in styled components?


I am trying to work with variations of colors of an icon depending on the atributes of a component, but I don't know how to write it.

I was able to do it directly in an item of the styles, following the example: code example switch case styled component

But inside the attributes of a component, I can't write it, doesn't work, here is how I tried: code example switch case styled component through attrs

What is my worry: today I only have two variations of color icon (last example), but I may have more in the future. Today, in the second case, when I want it to change the color (if it's different than the 2 options in the type) in anotrher place of the application, I have to change it directly: change icon color directly

How can I use in the second case the same strategy I used in the first one?

Thanks!

I'd like to use the same strategy for both


Solution

  • You can create a function outside your attributes and call it like.

    
    const getIconColor = (type) => {
      switch(type) {
      // .... do your logic
      }
    }
    
    //...
    
    const Icon = styled(MaterialIcons).attrs(({theme, type}) => ({
      color: getIconColor(type)
    }))