Skip to content

Instantly share code, notes, and snippets.

@anpct
Created November 3, 2021 19:10
Show Gist options
  • Save anpct/077c0b5b25ccba96c56016f4bcef5620 to your computer and use it in GitHub Desktop.
Save anpct/077c0b5b25ccba96c56016f4bcef5620 to your computer and use it in GitHub Desktop.
Reusable Dropdown
import React, { useState } from "react";
import useListener from "../../hooks/useListener";
import styled from "styled-components";
const DropdownContainer = styled.div`
width: 100px;
height: 100%;
position: relative;
display: flex;
align-items: center;
justify-content: center;
`;
const SelectedItem = styled.div`
width: 80%;
height: 80%;
display: flex;
align-items: center;
justify-content: center;
border-radius: 4px;
cursor: pointer;
border: thin solid ${(props) => props.theme.primary};
padding: 0.5rem;
transition: all 145ms ease;
&:hover {
background-color: rgb(255, 255, 255, 0.1);
}
`;
const ValueList = styled.ul`
width: 200px;
margin: 0;
padding: 0;
list-style-type: none;
position: absolute;
z-index: 99999;
height: 200px;
overflow: auto;
background: ${(props) => props.theme.background};
top: 55px;
left: 0;
`;
const Value = styled.li`
padding: 1rem;
display: flex;
align-items: center;
justify-content: flex-start;
border-bottom: thin solid ${(props) => props.theme.border};
cursor: pointer;
transition: all 145ms ease;
&:hover {
background-color: rgb(255, 255, 255, 0.1);
}
`;
const Dropdown = (props) => {
const { list, onUpdate, selectedItem } = props;
const [isOpen, setIsOpen] = useState(false);
const onClick = (item) => {
onUpdate(item);
};
const toggle = () => {
setIsOpen(!isOpen);
};
const ref = useListener(() => setIsOpen(false));
return (
<DropdownContainer ref={ref}>
<SelectedItem onClick={toggle}>
{selectedItem}
{" "}&#9663;
</SelectedItem>
{isOpen && (
<ValueList>
{list.map((item) => (
<Value
key={item}
onClick={() => {
onClick(item);
setIsOpen(false);
}}>
{item}
</Value>
))}
</ValueList>
)}
</DropdownContainer>
);
};
export default Dropdown;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment