styled-component dropdown make parent:hover color stay while child:hover

Viewed 93

I'm trying to make the parent background color stay changed on hover as I continue to hover over the dropdown items.

https://zqy0v.csb.app/dropdowns < dropdown

import React from "react";
import styled from "styled-components";

//============================================ styles =============================================
const DivDropdownContent = styled.div`
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 24.7rem;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
`;

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

  &:hover ${DivDropdownContent} {
    display: block;
  }
`;

const SpanDropdownTitle = styled.div`
  font-size: 1.6rem;
  font-weight: bold;
  padding: 2rem 6rem;
  border-radius: 0.6rem;
  border: 1px solid black;

  &:hover {
    cursor: pointer;
  }
`;

const ItemDropdown = styled.p`
  padding: 1rem;

  &:hover {
    cursor: pointer;
    background: lightgray;
  }
`;

//=========================================== component ===========================================
const BasicDropdown = props => {
  return (
    <DivDropdown>
      <SpanDropdownTitle>Basic&nbsp;Dropdown</SpanDropdownTitle>
      <DivDropdownContent>
        <ItemDropdown>Item 1</ItemDropdown>
        <ItemDropdown>Item 2</ItemDropdown>
        <ItemDropdown>Item 3</ItemDropdown>
      </DivDropdownContent>
    </DivDropdown>
  );
};

export default BasicDropdown;

Basically I would like the background color to stay changed for the parent while hovering over the child items in the dropdown, much like is done here https://woocommerce.com/

Is there an easy way to do this, or do I have to start getting complicated with using state and onPointerEnter and onPointerLeave?

1 Answers

I finally ended up finding the solution, and am a bit embarrassed.

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

  &:hover ${DivDropdownContent} {
    display: block;
  }
`;

The Issue: ^This was only targeting the nested component when I added the background cover to the hover.

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

  &:hover {
    background: lightgray;
  }

  &:hover ${DivDropdownContent} {
    display: block;
  }
`;

The Fix: ^By adding the above, I was able to correct the behavior.

I'm going to leave this question up, because I wasn't able to find much tutorials on this through my internet searching. I think this is a fairly clean solution and think it will help others searching.

Related