Search code examples
reactjsstyled-components

React styled-components: refer to other components


According to styled-components doc's I can refer to another component to trigger, for example, a hover effect.

const Link = styled.a`
    display: flex;
    align-items: center;
    padding: 5px 10px;
    background: papayawhip;
    color: palevioletred;
`;

const Link2 = styled.a`
    display: flex;
    align-items: center;
    padding: 5px 10px;
    background: steelblue;
    color: white;

    ${Link}:hover & {
        background-color: greenyellow;
        color: black;
    }
`;

class Hello extends React.Component{
  render() {
    return(
      <div>
        <Link>Hello World</Link>
        <Link2>Hello Again</Link2>
      </div>
    )
  }
}

Basically, hovering mouse on my <Link> should trigger a change in background-color in <Link2>.

This is not happening. Any ideas why?

I prepared a code snippet here: https://codesandbox.io/s/qv34lox494


Solution

  • You can refer to styled-components which are children of your styled-component, not side-by-side.

    See a quote from the doc:

    Here, our Icon component defines its response to its parent Link being hovered

    For your problem, you can create a wrapper for both of your links, and use the adjacent sibling selector in CSS like this:

    const Wrapper = styled.div`
        & ${Link}:hover + ${Link2} {
            background-color: greenyellow;
            color: black;
        }
    `;
    

    https://codesandbox.io/s/mo7kny3lmx