Skip to content

Commit

Permalink
implement better dropdown
Browse files Browse the repository at this point in the history
  • Loading branch information
Alberto Iannaccone committed Oct 9, 2022
1 parent 6401242 commit 7e231d9
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 2 deletions.
26 changes: 25 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 60 additions & 1 deletion src/components/better/dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,70 @@ import uuid from "uuid"

import "./dropdown.scss"

const Dropdown = ({ }) => {
const Dropdown = ({ items = [], activatorText = "Dropdown" }) => {
const [isOpen, setIsOpen] = useState(false);
const listRef = useRef(null);
const activatorRef = useRef(null);

const handleWrapKeyUp = (event) => {
if (event.key === "Escape" && isOpen) {
setIsOpen(false);
activatorRef.current && activatorRef.current.focus();
}
};

const handleClickActivator = () => {
setIsOpen(!isOpen);
}

const handleClickOutside = (event) => {
if ((listRef.current && listRef.current.contains(event.target)) || (activatorRef.current && activatorRef.current.contains(event.target))) {
return
}
setIsOpen(false);
};

useEffect(() => {
if (isOpen) {
document.addEventListener("mouseup", handleClickOutside);
listRef.current && listRef.current.querySelector('a').focus();
} else {
document.removeEventListener("mouseup", handleClickOutside);
}
return () => {
document.removeEventListener("mouseup", handleClickOutside);
};
}, [isOpen]);


return (
<div
className="dropdown-wrap"
onKeyUp={handleWrapKeyUp}
>
<button
aria-haspopup="true"
aria-controls="dropdown-list"
className="dropdown-activator"
ref={activatorRef}
onClick={handleClickActivator}
>
{activatorText}
</button>
<ul
id="dropdown-list"
className={`dropdown-itemList ${isOpen ? "active" : ""}`}
ref={listRef}
role="list" >
{items.length === 0
? <li>No items</li>
: items.map(item => (
<li key={uuid()} role="listitem">
<a href={item.url}>{item.text}</a>
</li>
))}

</ul>

</div>
)
Expand Down

0 comments on commit 7e231d9

Please sign in to comment.