Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target another component on hover using emotion-js

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

like image 846
Aquasar Avatar asked Oct 16 '25 06:10

Aquasar


1 Answers

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;
like image 69
coreyward Avatar answered Oct 19 '25 11:10

coreyward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!