1.1.0 • Published 1 year ago

@tracksuitdev/use-dropdown v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

useDropdown

React hook for managing dropdown state. Can be used to manage state of any component that closes when clicked outside or outside some other component/s (see additionalRefs).

Usage

const App = () => {
  const buttonRef = useRef(null);
  const {dropdownRef, isOpen, open, close} = useDropdown({additionalRefs: [buttonRef]});

  const handleClick = isOpen ? close : open;

  return (
    <div>
      <button onClick={handleClick} ref={buttonRef}>
        {isOpen ? "Close" : "Open"}
      </button>
      {isOpen && (
        <ul ref={dropdownRef}>
          <li>dropdown item 1</li>
          <li>dropdown item 2</li>
          <li>dropdown item 3</li>
        </ul>
      )}
    </div>
  );
};

Docs

useDropdown<T>(props: UseDropdownProps): UseDropdown<T>

Hook for managing dropdown state.

Adds window listener that will close dropdown on clicks outside of dropdownRef and additional refs.

Type parameters

NameTypeDescription
Textends HTMLElement = HTMLUListElementType of dropdown element

Props

UseDropdownProps

NameTypeDescription
event"click" or "mousedown"Event that triggers dropdown close if outside of dropdown, default is "click"
additionalRefs?RefObject<HTMLElement>[]These refs will be used when determining what constitutes a click outside of dropdown.
disabled?booleanIf true, open and close will do nothing
onClose?() => voidExecuted when close is called
onOpen?() => voidExecuted when open is called

Return value

UseDropdown<T>

NameTypeDescription
dropdownRefRefObject<T>Ref for dropdown element
isOpenbooleanDropdown state
open() => voidSets isOpen to true
close() => voidSets isOpen to false