Search code examples
cssreactjsstyled-components

How to conditionally render using object properties in styled-components?


I am trying to conditonally render in styled-components. This code seems to work in this case.

background-color: ${props => (props.active ? 'Black' : 'Green')};

I want to rather use object properties from a JSON file and provide 2 colours to the above condition. Something similar to these below instead of Black and Green.

${colors['Brand/PrimaryBlack']}
${colors['Brand/PrimaryGreen']}

colored.json

{
  "colors": {
    "Brand/PrimaryBlack": "#424449",
    "Brand/PrimaryGreen": "#8ED6C9",
  }
}

styles.js

import styled from 'styled-components'
import { colors } from './colored.json'

const Tabs = styled.button`    
 background-color: ${props => (props.active ? 'Black' : 'Green')};
`

How can I achieve this?


Solution

  • The ternary works exactly the same as your previous code, but just references the keys in your colors JSON, i.e. background-color: ${props => colors[props.active ? "Brand/PrimaryBlack" : "Brand/PrimaryGreen"]};.

    {
      "colors": {
        "Brand/PrimaryBlack": "#424449",
        "Brand/PrimaryGreen": "#8ED6C9",
      }
    }
    
    import styled from 'styled-components'
    import { colors } from './colored.json'
    
    const Tabs = styled.button`    
      background-color: ${props => colors[props.active ? "Brand/PrimaryBlack" : "Brand/PrimaryGreen"]};
    `;