Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 657
Nick Avatar asked May 19 '26 17:05

Nick


1 Answers

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

like image 107
John Ruddell Avatar answered May 23 '26 15:05

John Ruddell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!