카테고리 없음

React.js & Node.js 10일차

tonyhan18 2022. 1. 10. 13:59
728x90
import { useState } from "react";
import styled from "styled-components";

const Dropdown = () => {
  const [isShow, setIsShow] = useState(true);

  const handleClick = () => {
    setIsShow((prev) => !prev);
  };

  return (
    <Wrapper>
      <Btn onClick={handleClick}>Dropdown Button</Btn>
      {isShow && (
        <Menu>
          <Item>Action</Item>
          <Item>Action</Item>
          <Item>Action</Item>
        </Menu>
      )}
    </Wrapper>
  );
};

const Wrapper = styled.div`
  position: relative;
`;
const Btn = styled.div`
  max-width: 155px;
  padding: 6px 12px;
  font-size: 16px;
  background: #198754;
  border: none;
  color: #fff;
  border-radius: 4px;
  line-height: 1.5;
  cursor: pointer;
`;
const Menu = styled.ul`
  background-color: #fff;
  border: 1px solid rgb(221, 221, 221);
  border-radius: 4px;
  position: absolute;
`;
const Item = styled.li`
  padding: 5px 15px;
  width: 155px;
  cursor: pointer;
  & + & {
    border-top: 1px solid #ddd;
  }
  :hover {
    background: #ddd;
  }
`;

export default Dropdown;

 

Dropdown 구현 1

인스타 ver - 화면을 덮는 디자인

 

이제 z-index를 입력할 것인데 z-index의 특성상 position이 static이 아닌 얘들끼리 경쟁한다. 그래서 위쪽 코드는 position이 중첩되고 랜더링 순서로 말하는 z-index 역시 나중에 랜더링된 놈이 더 높다.

 

이 상태에서 z-index를 두어서 메뉴보다 높게 두면 Backdrop이 메뉴를 덮게 된다.

import { useState } from "react";
import styled from "styled-components";

const Dropdown = () => {
  const [isShow, setIsShow] = useState(true);
  const handleClick = () => {
    setIsShow((prev) => !prev);
    console.log("click");
  };

  return (
    <Wrapper>
      <Btn onClick={handleClick}>Dropdown Button</Btn>
      {isShow && (
        <>
          <Backdrop onClick={handleClick} />
          <Menu>
            <Item>Action</Item>
            <Item>Action</Item>
            <Item>Action</Item>
          </Menu>
        </>
      )}
    </Wrapper>
  );
};

const Wrapper = styled.div`
  position: relative;
`;
const Btn = styled.div`
  max-width: 155px;
  padding: 6px 12px;
  font-size: 16px;
  background: #198754;
  border: none;
  color: #fff;
  border-radius: 4px;
  line-height: 1.5;
  cursor: pointer;
`;
const Menu = styled.ul`
  background-color: #fff;
  border: 1px solid rgb(221, 221, 221);
  border-radius: 4px;
  position: absolute;
  z-index: 101;
`;
const Item = styled.li`
  padding: 5px 15px;
  width: 155px;
  cursor: pointer;
  & + & {
    border-top: 1px solid #ddd;
  }
  :hover {
    background: #ddd;
  }
`;

const Backdrop = styled.div`
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
`;

export default Dropdown;

아예 덮어버리는 방법이다. 이렇게 하면 다른곳을 눌렀을때도 이 창은 계속 남아있을 수 있다.

 

 

Dropdown 구현 2

728x90