react-bulma-components icon indicating copy to clipboard operation
react-bulma-components copied to clipboard

Missing default active state management of Navbar.Dropdown

Open FunctionDJ opened this issue 2 years ago • 0 comments

Describe the bug There's no default implementation for the Navbar.Link + Dropdown combination. By default it can't be toggled, but there's a working hoverable prop. Without that prop, the active prop of Navbar.Link must be controlled, but a primitive onClick={toggleNavbar} implementation is not optimal because the dropdown won't collapse when clicking outside the dropdown or navigating between pages, which is standard behaviour.

This can be seen in the documentation, which is why i'm not providing reproduction details: https://couds.github.io/react-bulma-components/?path=/story/components-navbar--default

Here's my click handling implementation as a custom hook, but i don't know if this is truly optimal for usability and accessibility. I personally like this behaviour though:

export const useDropdownState = () => {
  const [active, setActive] = useState(false);
  const linkRef = useRef<RenderAsComponent>(null);

  useEffect(() => {
    const handler: EventListener = event => {
      if (event.target === linkRef.current) {
        // if the clicked element is the parent Navbar.Link
        // then don't set active to false, because otherwise
        // you can't open the dropdown at all
        return;
      }

      setActive(false);
    };

    window.addEventListener("click", handler);

    return () => {
      window.removeEventListener("click", handler);
    };
  }, []);

  return { active, setActive, linkRef };
};

FunctionDJ avatar Apr 02 '22 18:04 FunctionDJ