3
votes

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>.

1
There is a way to do this using refs to pull out the styles of the parent in the child, but I would encourage you to just setup some CSS and give classes to your components. This is why CSS exists, you should not be trying to style your app with only incline styles.Chase
@Chase, I thought the whole point of styled-components was to stop writing CSS filesGeorge
you want to use JSS, not in-line styles. The idea is stop stop writing global CSS, but component level. However, that doesn't mean you can only use inline-styles. You can write CSS directly in your component.Chase

1 Answers

2
votes

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