useDropdown

The useDropdown hook is used inside the Dropdown component. This hook handles the logic inside the Dropdown component.

Code

import { useState } from "react";

export default function useDropdown(initialButtonText, onClickFunction){
    const [isOpen, setIsOpen] = useState(false);
    const [dropdownText, setDropdownText] = useState(initialButtonText);

    async function handleDropdownButtonClick(e){
        setIsOpen(!isOpen);
        setDropdownText(e.target.innerText);
        onClickFunction(e.target.innerText);
    }

    return [isOpen, setIsOpen, handleDropdownButtonClick, dropdownText];
}

Explanation

  • As you can see above it uses the useState hook of the React internally for toggling the state of each accordion label.

  • It accepts two parameters, a initialButtonText(string) and a onClickFunction(function to handle click logic on list items).

  • It returns the following:

    • isOpen -> a state value defining the current state of dropdown which is open or close.

    • setIsOpen -> an updater function to update the isOpen state value.

    • handleDropdownButtonClick -> a on click handler function given on list items inside the dropdown.

    • dropdownText -> the initial text shown on the dropdown button. After interactivity on items it will be no longer shown.

Last updated