Skip to content

Instantly share code, notes, and snippets.

@jonahallibone
Created February 6, 2020 00:01
Show Gist options
  • Save jonahallibone/18eec132adb8bf74091538b193faa9a2 to your computer and use it in GitHub Desktop.
Save jonahallibone/18eec132adb8bf74091538b193faa9a2 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
import styles from "./dropdown.module.scss";
const Dropdown = ({ children, title, ...rest }) => {
const focusStyle = styles.dropdown__focus;
const [focusClass, setFocusClass] = useState("");
const [focus, setFocus] = useState(false);
useEffect(() => {
if(focus) {
setFocusClass(focusStyle);
} else {
setFocusClass("");
}
}, [focus]);
const handleKeyDown = event => {
if(event.key === "Enter") {
setFocus(!focus);
}
};
return (
<div
{...rest}
tabIndex="0"
role="button"
onKeyPress={handleKeyDown}
onClick={() => setFocus(!focus)}
onBlur={() =>setFocus(false)}
className={`${styles.dropdown} ${focusClass}`}
>
<span>{title}</span>
<span className={styles.dropdown__icon}>
<i className="fas fa-chevron-down" />
</span>
<ul className={styles.dropdown__ul}>{children}</ul>
</div>
);
};
const Option = ({ children, ...rest }) => (
<li className={styles.dropdown__li} {...rest}>
{children}
</li>
);
export { Dropdown as default, Option };
.dropdown {
position: relative;
border: 1px solid #DDD;
border-radius: 5px;
padding: .5rem .75rem;
display: flex;
align-items: center;
cursor: pointer;
outline: none;
&:not(.dropdown__focus):hover {
border: 1px solid #1e90ff;
color: #1e90ff;
}
}
.dropdown__ul {
list-style: none;
margin: 0;
padding: 0;
position: absolute;
top: calc(100% + 5px);
right: 0;
z-index: 999;
visibility: hidden;
border: 1px solid #DDD;
outline: none;
background: #FFF;
padding: .5rem;
border-radius: 5px;
}
.dropdown__li {
padding: .5rem;
border-radius: 5px;
white-space: nowrap;
&:hover {
color: #1e90ff;
background: rgba($color: #1e90ff, $alpha: .1);
}
&.disabled {
color: #999;
cursor: not-allowed;
}
}
.dropdown__icon {
font-size: 12px;
margin-left: .5rem;
}
.dropdown__focus {
box-shadow: 0 0 0 3px rgba($color: #1e90ff, $alpha: .5);
ul {
visibility: visible;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment