Styled-Components: specify styles of children on parents hover

kurumkan picture kurumkan · Jul 11, 2017 · Viewed 22.3k times · Source

I have a simple component Here are 2 version of it - with and without styled-components:

Without Styled Components

<div id="container">
    <div id="kid"></div>
</div>


#container {
    width: 100px;
    height: 100px;
}

#kid {
    width: 20px;
    height: 20px;
}

#container:hover #kid{
    background: green;
}

With Styled Components

const Container = styled.div`
    width: 100px;
    height: 100px;
`;

const Kid = styled.div`
    width: 20px;
    height: 20px;
`;

<Container>
    <Kid />
</Container

How to implement the same on hover behaviour that was in the previous example?

Answer

mxstbr picture mxstbr · Jul 11, 2017

As of styled-components v2 you can interpolate other styled components to refer to their automatically generated class names. In your case you'll probably want to do something like this:

const Container = styled.div`
  &:hover ${Kid} {
    display: none;
  }
`

See the documentation for more information!

This is copy and pasted from my answer here.