Created
April 19, 2021 14:28
-
-
Save jogilvyt/4df315db271aea00f2120f0715f9c87b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext, useState, useContext, useMemo } from "react"; | |
const SelectListContext = createContext(); | |
const SelectList = ({ children }) => { | |
const [isOpen, setIsOpen] = useState(false); | |
const contextValue = useMemo( | |
() => ({ | |
isOpen, | |
setIsOpen, | |
}), | |
[isOpen] | |
); | |
return ( | |
<SelectListContext.Provider value={contextValue}> | |
<div className="SelectList">{children}</div> | |
</SelectListContext.Provider> | |
); | |
}; | |
const useSelectListContext = () => { | |
const context = useContext(SelectListContext); | |
if (!context) { | |
throw new Error( | |
`SelectList components cannot be rendered outside the SelectList component` | |
); | |
} | |
return context; | |
}; | |
const SelectListToggle = ({ children }) => { | |
const { setIsOpen } = useSelectListContext(); | |
return ( | |
<div | |
onClick={() => setIsOpen(prevOpen => !prevOpen)} | |
className="SelectList-Toggle" | |
> | |
{children} ▾ | |
</div> | |
); | |
}; | |
const SelectListDropdown = ({ children }) => { | |
const { isOpen } = useSelectListContext(); | |
return isOpen ? ( | |
<div className="SelectList-Dropdown" style={{ position: "absolute" }}> | |
{children} | |
</div> | |
) : null; | |
}; | |
const SelectListItem = ({ children, onClick }) => { | |
const { setIsOpen } = useSelectListContext(); | |
return ( | |
<div | |
className="SelectList-Item" | |
onClick={() => { | |
setIsOpen(false); | |
onClick(); | |
}} | |
> | |
{children} | |
</div> | |
); | |
}; | |
SelectList.Toggle = SelectListToggle; | |
SelectList.Dropdown = SelectListDropdown; | |
SelectList.Item = SelectListItem; | |
export default SelectList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment