Search code examples
reactjsstyled-componentsreact-props

Styled-Components: Conditional styling with multiple props / states


I can't seem to find anything about this on Google... Chances are it's there and I'm just not Googling the right thing. I just keep finding what I've already done for one prop.

I currently have styles based on props and states. And they work as expected. But I've found myself in a scenario where I need a style where two props (true/false) are required at the same time for the desired result.

I was wondering if that was possible?

The below works:

${({ prop1 }) => !prop1 &&`
    // Some Styles when !prop1
`};

${({ prop2 }) => prop2 &&`
    // Some Styles when prop2
`};

What I'm trying to do is something like the below:

${({ prop1, prop2 }) => !prop1, prop2 &&`
    // Some Styles when !prop1 && prop2
`};

or

${({ prop1 && prop2 }) => !prop1 && prop2 &&`
    // Some Styles when !prop1 && prop2
`};

But that doesn't seem to want to work. I don't think I'm far off... Maybe I am? Any help would be great!

Thanks a lot.


Solution

  • you should use the css method to do conditionals

    import styled, { css } from 'styled-components'
    
    ${({ prop1, prop2 }) => !prop1 && prop2 && css`
        // Some Styles when !prop1 && prop2
    `};
    

    notice syntactially you are destructuring the props in your function.

    ({prop1 && prop2}) == invalid syntax