Search code examples
javascriptreactjsstyled-components

change nested component's style based on parent props in styled-components?


Let's say I have a wrapper component that has some other components inside of it:

const Card = styled.div`
    background-color: ${props => props.selected ? 'green' : 'none'}
`

<Card>
    <Header>
        <Logo/>
    </Header>
    <Footer/>
</Card>

They are all styled components. The card turns green, when I pass selected prop to it. How can I change styles of <Logo> according to that prop, passed to <Card>?

For example, in pure css I did it like this:

.card.selected {
    background-color: green;
}

.card.selected .logo {
    opacity: 1;
} 

What is the best way to replicate this behavior in styled-components? I don't like the idea to pass selected prop to all children of <Card>.


Solution

  • Turned out this is pretty easy, actually.

    const Card = styled.div`
        background-color: ${props => props.selected ? 'green' : 'none'};
    
        ${Logo} {
            opacity: ${props => props.selected ? 1 : 0};
        }
    `
    

    And this feature is documented here