Skip to content

Instantly share code, notes, and snippets.

@kwoncharles
Created March 1, 2020 09:21
Show Gist options
  • Save kwoncharles/cc37357a661c4cea54212d25813c5481 to your computer and use it in GitHub Desktop.
Save kwoncharles/cc37357a661c4cea54212d25813c5481 to your computer and use it in GitHub Desktop.
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