Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 242
Lc0rE Avatar asked Aug 23 '17 13:08

Lc0rE


2 Answers

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

like image 145
Adrien Lacroix Avatar answered Sep 20 '22 11:09

Adrien Lacroix


The other way is to modify your selector on Link2 to use siblings (now it's nested item selector). In that case you can get rid of extra wrapper

    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>
    )
  }
}
like image 24
Grigory Avatar answered Sep 21 '22 11:09

Grigory