Created
March 1, 2020 09:21
-
-
Save kwoncharles/cc37357a661c4cea54212d25813c5481 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 { useState, useCallback } from 'react'; | |
export interface DropdownBundle<T> { | |
isOpen: boolean; | |
selectedValue: T; | |
onClickDropdown: () => void; | |
onClickOption: (v: T) => void; | |
onRequestClose: () => void; | |
} | |
interface Options<T> { | |
initialValue?: T; | |
} | |
function useDropdown<T>(options?: Options<T>): DropdownBundle<T> { | |
const { initialValue } = options || {}; | |
const [isOpen, setIsOpen] = useState<boolean>(false); | |
const [selectedValue, setSelectedValue] = useState<T>(initialValue); | |
const onClickDropdown = useCallback(() => { | |
setIsOpen(true); | |
}, []); | |
const onClickOption = useCallback((value: T) => { | |
setSelectedValue(value); | |
setIsOpen(false); | |
}, []); | |
const onRequestClose = useCallback(() => { | |
setIsOpen(false); | |
}, []); | |
return { | |
isOpen, | |
selectedValue, | |
onClickDropdown, | |
onClickOption, | |
onRequestClose, | |
} | |
} | |
export default useDropdown; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment