select 태그의 디자인 어려움 문제로 select를 사용하지 않고 css(Styled-Components)를 이용해 드롭다운을 구현해봤습니다.
const Dropdown = () => {
1️⃣const [isActive, setIsActive] = useState(false);
2️⃣const [item, setItem] = useState(null);
3️⃣const onActiveToggle = useCallback(() => {
setIsActive((prev) => !prev);
}, []);
4️⃣const onSelectItem = useCallback((e) => {
const targetId = e.target.id;
if (targetId === "item_name") {
setItem(e.target.parentElement.innertText);
} else if (targetId === "item") {
setItem(e.target.innertText);
}
5️⃣setIsActive((prev) => !prev);
}, []);
return (
<DropdownContainer>
<DropdownBody onClick={onActiveToggle}>
6️⃣{item ? (
<>
<ItemName>{item}</ItemName>
</>
) : (
<>
<DropdownSelect>선택해주세요.</DropdownSelect>
<AiOutlineDown />
</>
)}
</DropdownBody>
7️⃣<DropdownMenu isActive={isActive}>
{dropdownItems.map((item) => (
<DropdownItemContainer id="item" key={item.id} onClick={onSelectItem}>
<ItemName id="item_name">{item.name}</ItemName>
</DropdownItemContainer>
))}
</DropdownMenu>
</DropdownContainer>
);
};
export default Dropdown;
display: block
, false일땐 display:none
으로 드롭다운 구현을 합니다.import styled from "styled-components";
export const DropdownContainer = styled.div`
width: 400px;
&:hover {
cursor: pointer;
}
`;
export const DropdownBody = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 9px 14px;
border: 2px solid #d2d2d2;
`;
export const DropdownSelect = styled.p`
font-weight: bold;
`;
export const DropdownMenu = styled.ul`
1️⃣display: ${(props) => (props.isActive ? `block` : `none`)};
width: 400px;
background-color: white;
2️⃣position: absolute;
border: 2px solid #f4acbb;
`;
export const DropdownItemContainer = styled.li`
display: flex;
justify-content: space-between;
align-items: center;
padding: 9px 14px;
border-bottom: 2px solid #d2d2d2;
border-top: none;
&:last-child {
border-bottom: none;
}
`;
export const ItemName = styled.p`
font-weight: bold;
`;
active
를 이용해 block, none
을 구분합니다.