36

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?

kurumkan
  • 2,635
  • 3
  • 31
  • 55

3 Answers3

64

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.

Community
  • 1
  • 1
mxstbr
  • 11,087
  • 4
  • 39
  • 37
  • 5
    I was looking for this through the documentation and project's issues. Shouldn't it be part of the styledcomponents basic or advanced section instead of faq? Thanks for the good work. – Pietro Nov 09 '17 at 08:41
7

try:

const Container = styled.div`
    width: 100px;
    height: 100px;
    &:hover #kid {
        background: green;
    }
`;

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

<Container>
    <Kid id="kid" />
</Container>
Tom Berghuis
  • 491
  • 3
  • 10
  • 26
0
import styled from "styled-components";

const Parent = styled.div`
width: 100%;
height: 100%;
&:hover .btn {
    transform: scale(0.9);
}
`;

const button = styled.div`
width: 20px;
height: 20px;
`;
<Parent>
<button className="btn" />
</Parent>
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 16 '22 at 04:13