4

I understand this is very similar to Target another styled component on hover

However I would like to achieve the same effect with emotion-js

More specifically I am trying to recreate this example using emotion styled components

Here is my code and what I have tried.

import React from 'react';
import styled from '@emotion/styled';
import { Link } from 'gatsby';

const Dropdown = styled.div`
  postition: relative;
  display: inline-block;
`;

const Button = styled.div`
  background-color: green;
  color: white;
  &:hover {
    ${DropDownContent} {
      display: block;
    }
  }
`;

const DropDownContent = styled.div`
  display: none;
  position: absolute;
`;

const DropDownMenu = () => {
  return (
    <Dropdown>
      <Button>Dropdown</Button>
      <DropDownContent>
        <Link to="/">Link 1</Link>
      </DropDownContent>
    </Dropdown>
  );
};

export default DropDownMenu;

I would like the link to show up when I hover the button, but that is not working and I cannot figure out why

Theorder
  • 669
  • 2
  • 9
  • 19

2 Answers2

4

There are three issues here.

  1. You're referencing DropdownContent before you've defined it. Rearrange your code so that the DropdownContent declaration comes before the tagged template literals that use it and you should be good to go.

  2. The resulting css selector (something like button:hover .DropDownContent) does not match your HTML document, where DropDownContent is a sibling of Button.

  3. Your position property on Dropdown is misspelled.

With all three issues resolved, your code may look something like this:

import React from 'react';
import styled from '@emotion/styled';
import { Link } from 'gatsby';

const Dropdown = styled.div`
  position: relative;
  display: inline-block;
`;

const DropDownContent = styled.div`
  display: none;
  position: absolute;
`;

const Button = styled.div`
  background-color: green;
  color: white;
  &:hover + ${DropDownContent} {
    display: block;
  }
`;

const DropDownMenu = () => {
  return (
    <Dropdown>
      <Button>Dropdown</Button>
      <DropDownContent>
        <Link to="/">Link 1</Link>
      </DropDownContent>
    </Dropdown>
  );
};

export default DropDownMenu;
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • Getting rid of the pseudo selector + worked for me and changing my markdown to wrap the Button around the DropDownContent. I think this makes sense because we want the DropDownContent style to change when hovering over the button and the links – Theorder Oct 20 '19 at 08:12
0

as @coreyward mentioned, rearrange the code.... and the

import styled from "@emotion/styled/macro";

and this will do the trick

This solution was already posted at Component selectors can only be used in conjunction with babel-plugin-emotion error while using emotion by https://stackoverflow.com/users/165215/ijk