0

I have a below structure.

<Nav>
  <Title/>
  <DropDown />
</Nav>

<Nav /> is a class component and I need to show Dropdown when I hover over <Nav />.

Here is the code snippet of <Nav />.

export default class HeaderLink extends React.PureComponent {
...
}

Here is the code snippet of <DropDown />.

const Container = styled.ul`
    opacity: 0;
    visibility: hidden;
    transform: translateY(20px);
    transition: all .3s ease-in-out;

    ${Nav}:hover & {
        opacity: 1;
        visibility: visible;
        transform: translateY(-2px);
    }
`;

const DropDown = ({ items }) => (
    <Container>
        {items.map(({ title, url }) => (
            <a href={url}>{title}</a>
        ))}
    </Container>
);

DropDown.propTypes = {
    items: PropTypes.array.isRequired
};

export default DropDown;

This is not working but I figured that If I define <Nav /> component as a styled-component, it works

i.e. const Nav = styled.ul''

But it's not working for the class component.

Any thoughts on this?

Thanks.

Patrick Blind
  • 289
  • 4
  • 12

1 Answers1

1

You're attempting to use a parent as a selector, which is not currently possible in CSS (see: Is there a CSS parent selector?). Your :hover should be on your Nav component, which in turn targets the appropriate child element.

See example CodeSandbox here: https://codesandbox.io/s/x9lmkply4.

tombraider
  • 1,048
  • 9
  • 18
  • Thanks. it works but `&:hover { > ul { ... } }`. you specified `ul` but can we point a custom component directly? so we can implement this in a styled-component way. – Patrick Blind Jan 21 '19 at 15:16
  • Yes, if you're using the latest version of styled components then you can use interpolation. E.g. `${ChildComponent} { ...rules }`. I've updated the sandbox appropriately. – tombraider Jan 21 '19 at 15:28