Nested onHover selector not working with styled-components

Viewed 461

I'm trying to change the style of a styled-components element when another element is hovered over, however it doesn't seem to apply those changes.

The piece of relevant code is,

const Logo = styled.div`
  . . .
  &:hover {
    color: red;

    ${TextStyled} {
      display: flex;
    }
  }
`;

The color of the Logo component successfully changes to red on hover, however the display property of the TextStyled component doesn't seem to be affected.

What am I doing wrong here? I've tried adding a tilde before ${TextStyled}, but that selector didn't work either.

I've also tried applying the style through the parent Main component, but that didn't work either:

const Main = styled.div`
  height: 100vh;
  width: 100vw;
  background: #000;

  ${Logo} {
    &:hover {
      color: red;

      ${TextStyled} {
        display: flex;
      }
    }
  }
`;

cool-grass-2x1ob

1 Answers

I think it doesn't work because it's not a child of the hovered element, so you could solve like this:

&:hover + ${TextStyled}   {
    color: red;
    display: block;
    
  }

Another way is put TextStyled into Logo like:

<Logo>Logo<TextStyled /></Logo>

And in logo const:

&:hover {
    color: red;

    ${TextStyled} {
      display: flex;
    }

edit after comment:

For resolve your problem create another div then put logo and textstyled into that.

<Cont>
      <Logo>Logo</Logo>
      <TextStyled />
    </Cont>

Then create rule:

const Cont = styled.div`
  width: 100%; // just example
  &:hover {
    ${TextStyled} {
      display: block;
    }
  }
`;

and Logo:

const Logo = styled.div`
  font-weight: 700;
  color: #ffffff;
  font-size: 4em;
  letter-spacing: 5px;
  transition: 0.25s;
  z-index: 200;

  &:hover {
    color: red;
    filter: blur(10px);
  }
`;
Related