Home > Software engineering >  Menu not opening when clicking on react-icons icon
Menu not opening when clicking on react-icons icon

Time:08-15

I have a menu that should open when I click on a button. and close when I click the button again or click outside the menu. It works right but it has a bug when I click on svg icon inside button, and it does not work, the menu does not open.

 const MoreActionBtn = () => {
  const [showMoreAction, setShowMoreAction] = useState(false);
  const moreBtns = useRef();
  const { current } = moreBtns;

  useEffect(() => {
    const outSideClickHandler = (e) => {
      if (current && !current.contains(e.target)) {
        setShowMoreAction(false);
      }
    };
    document.addEventListener("click", outSideClickHandler);
    return () => {
      document.removeEventListener("click", outSideClickHandler);
    };
  }, [current]);

  function toggleMoreAcrion() {
    setShowMoreAction((prev) => !prev);
  }

  return (
    <div ref={moreBtns} className="more-action-wrapper">
      {showMoreAction && (
        <div>
          <button>
            <MdDone />
          </button>
          <button>
            <MdOutlineModeEdit />
          </button>
        </div>
      )}
      <button onClick={toggleMoreAcrion}>
        {showMoreAction ? <MdOutlineCancel /> : <MdStars />}
      </button>
    </div>
  );
};

Here is a codesandbox of my code. Is there a better solution?

CodePudding user response:

It seems like the problem is simpler than I thought. What's happening is that somehow the svg rendered by MdStar from react-icons is catching the click. To avoid this add the below CSS:

.more-action-wrapper svg {
  pointer-events: none;
}

Working forked of your CodeSandbox here.

  • Related