couds / react-bulma-components

React components for Bulma framework
MIT License
1.2k stars 129 forks source link

Missing default active state management of Navbar.Dropdown #382

Open FunctionDJ opened 2 years ago

FunctionDJ commented 2 years ago

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 };
};