Tarun
Tarun

Reputation: 1089

Multiple Conditions not working in Styled-Component

I am creating Form Buttons where some would be Primary and some would be Secondary. On them, I would apply the UX color codes. The first one works, the second one doesn't.

Am I doing something wrong?

Here is the code:

const FormActionBtns = styled.span`
  height: 50px;
  max-width: 100px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: red;
  color: white;

  ${props => props.theme && props.theme.ACCENT && `
    font-size: ${props.theme.FONT_SIZE.TOPIC_HEADER};
    color: ${props.theme.PRIMARY_STAGE.FORM_COMPONENTS.FONT.REVERSE_BRIGHT};

    ${props.isPrimary && `
        background-color: ${props.theme.ACCENT.IDLE}; 
    `}

    ${props.isSecondary && `
        background-color: ${props.theme.COMPLEMENTARY.IDLE}; 
    `}
  `}
`;

export const SubmitBtn = (props) => {
    console.log(props);
    return(
        <FormActionBtns isPrimary={true}>
            {props.submitTxt}
        </FormActionBtns>
    )
}

export const RevertBtn = (props) => {
    return (
        <FormActionBtns isSecondary={true}>
            {props.revertTxt}
        </FormActionBtns>
    )
}

The Submit button works brilliantly as the correct accent color gets applied based on the theme. The Reset button is not working properly having passed isSecondary=true.

Note: When I remove the condition isPrimary from the style, Reset then gives proper result

Upvotes: 1

Views: 3086

Answers (3)

StackedQ
StackedQ

Reputation: 4139

You're missing a semi-colon:

 ${props.isPrimary && `
     background-color: ${props.theme.ACCENT.IDLE}; 
 `}; // here

  ${props.isSecondary && `
     background-color: ${props.theme.COMPLEMENTARY.IDLE}; 
 `}

Upvotes: 0

Joseph D.
Joseph D.

Reputation: 12174

You can also use .attrs.

styled.span.attrs(({ isPrimary, theme }) => ({
  background-color: isPrimary ? theme.ACCENT.IDLE : theme.COMPLEMENTARY.IDLE;
}))
`
 // other styles
`

Upvotes: 1

GalAbra
GalAbra

Reputation: 5148

In order to implement CSS dynamically in React, I'd just use the style attribute, similarly to this code:

const FormActionBtns = (props) => {
  const styleProp = { height: '50px', maxWidth: '100px' }; // etc.
  if (props.isPrimary) {
    styleProp.backgroundColor = props.theme.ACCENT.IDLE;
  } else if (props.isSecondary) {
    styleProp.backgroundColor = props.theme.COMPLEMENTARY.IDLE;
  }

  return (
    <span style={styleProp}>
      {props.children}
    </span>
  );
}

Upvotes: 1

Related Questions