Search code examples
reactjsstyled-components

With Styled Components, why does a conditional style not have access to props?


with Styled Components I have the following:

const StyledTextArea = styled.textarea`
  color: ${(props) => props.theme.colors.black};

  font-size: 24px;

  ${({ error }) => error && `
    // border-color: red; // for testing to confirm props issue
    border-color: ${(props) => props.theme.colors.red[1]};
  `}

`;

  <StyledTextArea
    error={error}
  />

The textarea color is being set correctly via the theme.

When the prop error is set to true, the commented out border-color works fine, but the dynamic line using props no longer works within the conditional:

border-color: ${(props) => props.theme.colors.red[1]};

Why does the conditional not seem to have access to the props?


Solution

  • There a couple of ways to solve this, the easiest is to put the theme in the original params and use it from there.

    ${({ error, theme }) => error && `
        // border-color: red; // for testing to confirm props issue
        border-color: ${theme.colors.red[1]};
    `}