0
votes

I am trying to create a Button component using Styled-Components and Styled-System. In general, it works fine. However, when it comes to doing a basic prop test, I can't seem to get it to work.

For instance, the following code is not working for me:

background-color: ${props => (props.bg ? 'red' : 'blue')}

Whether or not I have set the bg prop, the background-color is always red. In other words, the following components both return a red background:

<Button>Button</Button>
<Button bg="primary.base">Primary</Button>

Any idea how I can conditionally check if a prop is set?

In case it helps, I am referring to the Button.js and layout.js files in the Components folder here: https://codesandbox.io/s/gatsbystarterdefault-rbzo8?fontsize=14

1

1 Answers

0
votes

Option 1: Are we sure that the red background is due to the hover of line 33 of the Button.js file? Change it to orange in order to be sure.

Option 2: Maybe yout custom styles are overwritten by the ones you passed from line 35 to 44:

  ${borders}
  ${boxShadow}
  ${buttonSize}
  ${fontSize}
  ${height}
  ${lineHeight}
  ${minWidth}
  ${space}
  ${color}
  ${buttonStyle}

Hoist that part before you custom Button styles and try it again.

Option 3: Set the default blue color and overwrite it if property bg exists. In order to do it, replace line 33 of the Button.js with this:

background-color: blue;
${props => props.bg && css`background-color: orange;`}

Note: The parenthesis in the aforementioned line 33 is not necessary:

background-color: ${props => props.bg ? 'red' : 'blue'}