[React] styled component children으로 선택하기

thousand_yj·2023년 8월 2일
0

Willing 프로젝트

목록 보기
16/18

하고 싶은 작업은 부모 요소(Item 영역)에 유저가 마우스를 올리면 자식 요소(IconKebapWrapper)가 보이게 하는 것이다. 굳이 state를 쓸 필요 없이 Item 내에 hover가 된 경우 해당 컴포넌트에 display:block; 속성을 주면 된다.

그러려면 내부에서 ${}를 사용하여 styled component를 잡아오면 된다!

코드는 이 부분이다.

const Item = styled.li`
  // ...

  &:hover > ${IconKebapWrapper} {
    display: block;
  }
  // ...
`;

전체 코드는 다음과 같다.

import { IGroup } from "../../models/atoms";
import styled from "styled-components";
import IconKebap from "../icons/IconKebap";

type IGroupItem = {
  item: IGroup;
};

function GroupItem({ item }: IGroupItem) {
  const kebapClickHandler = () => {};
  return (
    <Item>
      <CircleTitleWrapper>
        <ColorCircle colorstring={item.color} />
        {item.title}
      </CircleTitleWrapper>
      <IconKebapWrapper onClick={kebapClickHandler}>
        <IconKebap />
      </IconKebapWrapper>
    </Item>
  );
}

export default GroupItem;

const IconKebapWrapper = styled.div`
  display: none;
  cursor: pointer;
`;

const Item = styled.li`
  font-size: 12px;
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  margin-left: 13px;
  margin-right: 13px;
  justify-content: space-between;

  &:hover > ${IconKebapWrapper} {
    display: block;
  }
  @media (max-width: 1200px) {
    margin-bottom: 0px;
    margin-bottom: 0px;
    display: flex;
    margin-bottom: 18px;
    margin-left: 13px;
    margin-right: 13px;
  }
  @media (max-width: 768px) {
    margin-bottom: 0px;
    margin-bottom: 0px;
    display: flex;
  }
`;

const CircleTitleWrapper = styled.div`
  display: flex;
  align-items: center;
`;

const ColorCircle = styled.div<{ colorstring: string }>`
  min-width: 0.8em;
  min-height: 0.8em;
  width: 0.8em;
  height: 0.8em;
  border-radius: 50%;
  background-color: ${(props) => props.colorstring};
  margin-right: 8px;
`;
profile
함께 일하고 싶은 개발자가 되기 위해 노력합니다. 코딩테스트 관련 공부 및 이야기는 티스토리에도 업로드되어 있습니다.

0개의 댓글